查找父/子控件(元素、节点)
1 /// <summary> 2 /// 用于查找控件的工具类:找到父控件、子控件 3 /// </summary> 4 class ControlsSearchHelper 5 { 6 /// <summary> 7 /// 查找父控件 8 /// </summary> 9 /// <typeparam name="T">父控件的类型</typeparam> 10 /// <param name="obj">要找的是obj的父控件</param> 11 /// <param name="name">想找的父控件的Name属性</param> 12 /// <returns>目标父控件</returns> 13 public static T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement 14 { 15 DependencyObject parent = VisualTreeHelper.GetParent(obj); 16 17 while (parent != null) 18 { 19 if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name))) 20 { 21 return (T)parent; 22 } 23 24 // 在上一级父控件中没有找到指定名字的控件,就再往上一级找 25 parent = VisualTreeHelper.GetParent(parent); 26 } 27 28 return null; 29 } 30 31 32 /// <summary> 33 /// 查找子控件 34 /// </summary> 35 /// <typeparam name="T">子控件的类型</typeparam> 36 /// <param name="obj">要找的是obj的子控件</param> 37 /// <param name="name">想找的子控件的Name属性</param> 38 /// <returns>目标子控件</returns> 39 public static T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement 40 { 41 DependencyObject child = null; 42 T grandChild = null; 43 44 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++) 45 { 46 child = VisualTreeHelper.GetChild(obj, i); 47 48 if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name))) 49 { 50 return (T)child; 51 } 52 else 53 { 54 // 在下一级中没有找到指定名字的子控件,就再往下一级找 55 grandChild = GetChildObject<T>(child, name); 56 if (grandChild != null) 57 return grandChild; 58 } 59 } 60 61 return null; 62 63 } 64 65 66 /// <summary> 67 /// 获取所有同一类型的子控件 68 /// </summary> 69 /// <typeparam name="T">子控件的类型</typeparam> 70 /// <param name="obj">要找的是obj的子控件集合</param> 71 /// <param name="name">想找的子控件的Name属性</param> 72 /// <returns>子控件集合</returns> 73 public static List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement 74 { 75 DependencyObject child = null; 76 List<T> childList = new List<T>(); 77 78 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++) 79 { 80 child = VisualTreeHelper.GetChild(obj, i); 81 82 if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name))) 83 { 84 childList.Add((T)child); 85 } 86 87 childList.AddRange(GetChildObjects<T>(child, "")); 88 } 89 90 return childList; 91 92 } 93 } 94 } 95 96 public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject 97 { 98 if (depObj != null) 99 { 100 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 101 { 102 DependencyObject child = VisualTreeHelper.GetChild(depObj, i); 103 104 if (child != null && child is T) 105 yield return (T)child; 106 107 foreach (T childOfChild in FindVisualChildren<T>(child)) 108 yield return childOfChild; 109 } 110 } 111 }