按类型查找 WPF 窗口中的所有控件 [英] Find all controls in WPF Window by type
本文介绍了按类型查找 WPF 窗口中的所有控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法来按类型查找 Window 上的所有控件,
I'm looking for a way to find all controls on Window by their type,
例如:查找所有TextBoxes
,查找所有实现特定接口的控件等
for example: find all TextBoxes
, find all controls implementing specific interface etc.
推荐答案
这应该可以解决问题
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null)
return;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
yield return (T)child;
foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
然后你像这样枚举控件
foreach (var tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
}
这篇关于按类型查找 WPF 窗口中的所有控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文