我正在寻找一种通过其类型在Window上查找所有控件的方法,
例如: find all TextBoxes,找到实现特定接口的所有控件等。
TextBoxes
这应该可以解决问题
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject 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 (TextBlock tb in FindVisualChildren<TextBlock>(window)) { // do something with tb here }