Fortunately, WPF provides a direct method to achieve this purpose:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj == null) yield return (T)Enumerable.Empty<T>(); 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; } } }
To use this method, just enumerate the controller in the following way:
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window)) { // 对 TextBlock tb 执行操作 }
The above is the detailed content of How Can I Find WPF Controls by Their Type?. For more information, please follow other related articles on the PHP Chinese website!