WPF中查找控件的扩展类

2023-07-29,,

在wpf中查找控件要用到VisualTreeHelper类,但这个类并没有按照名字查找控件的方法,于是搜索网络,整理出下面这个类,感觉用起来很是方便。

贴出来,供大家参考。

    /// <summary>
/// WPF/Silverlight 查找控件扩展方法
/// </summary>
public static class VisualHelperTreeExtension
{
/// <summary>
/// 根据控件名称,查找父控件
/// elementName为空时,查找指定类型的父控件
/// </summary>
public static T GetParentByName<T>(this DependencyObject obj, string elementName)
where T : FrameworkElement
{
DependencyObject parent = VisualTreeHelper.GetParent(obj);
while (parent != null)
{
if ((parent is T) && (((T)parent).Name == elementName || string.IsNullOrEmpty(elementName)))
{
return (T)parent;
}
parent = VisualTreeHelper.GetParent(parent);
} return null;
} /// <summary>
/// 根据控件名称,查找子控件
/// elementName为空时,查找指定类型的子控件
/// </summary>
public static T GetChildByName<T>(this DependencyObject obj, string elementName)
where T : FrameworkElement
{
DependencyObject child = null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child is T && (((T)child).Name == elementName) || (string.IsNullOrEmpty(elementName)))
{
return (T)child;
}
else
{
T grandChild = GetChildByName<T>(child, elementName);
if (grandChild != null)
{
return grandChild;
}
}
}
return null;
} /// <summary>
/// 根据控件名称,查找子控件集合
/// elementName为空时,查找指定类型的所有子控件
/// </summary>
public static List<T> GetChildsByName<T>(this DependencyObject obj, string elementName)
where T : FrameworkElement
{
DependencyObject child = null;
List<T> childList = new List<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child is T && (((T)child).Name == elementName) || (string.IsNullOrEmpty(elementName)))
{
childList.Add((T)child);
}
else
{
List<T> grandChildList = GetChildsByName<T>(child, elementName);
if (grandChildList != null)
{
childList.AddRange(grandChildList);
}
}
}
return childList;
}
}

使用的时候非常简单,比如查找datagrid里模板列的一个叫“myTextBox”的文本框,可以这样写:

                var child = dataGrid.GetChildByName<TextBox>("myTextBox");
if (child != null)
{
child.Text = "abc";
}

注意:初期化页面的时候,如果查找控件的代码放在Loaded事件中,会找不到控件;应该放在LayoutUpdated事件中,这时候xaml已经加载完毕,所有的子控件才能取到。

但是LayoutUpdated事件只要页面有更新,它都会触发,如果要达到Loaded事件的效果,我们可以设置一个flag在控制代码只在初期化时执行一次,现在也没有想到更好的办法来实现,大概如下:

        bool firstLoad = true;
private void UserControl_LayoutUpdated(object sender, EventArgs e)
{
if (firstLoad)
{
//第一次加载要执行的代码
//...
firstLoad = false;
}
}

WPF中查找控件的扩展类的相关教程结束。

《WPF中查找控件的扩展类.doc》

下载本文的Word格式文档,以方便收藏与打印。