此方法会递归遍历该DependencyObject的所有VisualChildren(一般用于获取template中未知Name属性但已知类型的控件):
1 public static ChildControl FindVisualChild<ChildControl>(this DependencyObject DependencyObj) 2 where ChildControl : DependencyObject 3 { 4 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(DependencyObj); i++) 5 { 6 DependencyObject Child = VisualTreeHelper.GetChild(DependencyObj, i); 7 8 if (Child != null && Child is ChildControl) 9 { 10 return (ChildControl)Child; 11 } 12 else 13 { 14 ChildControl ChildOfChild = FindVisualChild<ChildControl>(Child); 15 16 if (ChildOfChild != null) 17 { 18 return ChildOfChild; 19 } 20 } 21 } 22 23 return null; 24 }
此方法可获取指定Name属性的子控件(一般用于获取容器控件中已知Name属性的子控件):
1 public static T GetNamedDescendantOfType<T>(this DependencyObject start, string name) where T : FrameworkElement 2 { 3 var descendants = start.GetDescendants(); 4 if (descendants != null) 5 { 6 foreach (FrameworkElement d in descendants) 7 { 8 if (d.Name.Equals(name)) 9 return d as T; 10 } 11 } 12 13 return null; 14 } 15 16 public static IEnumerable<DependencyObject> GetDescendants(this DependencyObject start) 17 { 18 var queue = new Queue<DependencyObject>(); 19 var count = VisualTreeHelper.GetChildrenCount(start); 20 21 for (int i = 0; i < count; i++) 22 { 23 var child = VisualTreeHelper.GetChild(start, i); 24 yield return child; 25 queue.Enqueue(child); 26 } 27 28 while (queue.Count > 0) 29 { 30 var parent = queue.Dequeue(); 31 var count2 = VisualTreeHelper.GetChildrenCount(parent); 32 33 for (int i = 0; i < count2; i++) 34 { 35 var child = VisualTreeHelper.GetChild(parent, i); 36 yield return child; 37 queue.Enqueue(child); 38 } 39 } 40 }