在WPF中,按名称或类型查找控件通常涉及使用FindName
方法或递归遍历VisualTree。下面提供一个通用的类库,其中包括按名称和按类型查找控件的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace WpfControlFinder
{
public static class ControlFinder
{
// 按名称查找控件
public static T FindByName<T>(FrameworkElement parent, string name) where T : FrameworkElement
{
return FindControls<T>(parent, c => c.Name == name).FirstOrDefault();
}
// 按类型查找控件
public static T FindByType<T>(FrameworkElement parent) where T : FrameworkElement
{
return FindControls<T>(parent, c => c.GetType() == typeof(T)).FirstOrDefault();
}
// 递归查找控件
private static IEnumerable<T> FindControls<T>(DependencyObject parent, Func<T, bool> condition) where T : FrameworkElement
{
var controls = new List<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T t && condition(t))
{
controls.Add(t);
}
controls.AddRange(FindControls<T>(child, condition));
}
return controls;
}
}
}
下面是一个简单的WPF应用的示例代码,演示了如何使用这个类库:
using System.Windows;
namespace WpfControlFinderExample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 在MainWindow中按名称查找Button
var buttonByName = ControlFinder.FindByName<Button>(this, "myButton");
// 在MainWindow中按类型查找TextBox
var textBoxByType = ControlFinder.FindByType<TextBox>(this);
// 执行一些操作
if (buttonByName != null)
{
buttonByName.Content = "已找到";
}
if (textBoxByType != null)
{
textBoxByType.Text = "已找到";
}
}
}
}
在这个例子中,ControlFinder
类提供了FindByName
和FindByType
两个方法,分别用于按名称和按类型查找控件。这可以在WPF应用程序中方便地查找和操作控件。
源代码获取:公众号回复消息【code:82118
】