1 /// <summary> 2 /// 获取指定类型的可视父对象 3 /// </summary> 4 /// <typeparam name="T">指定类型</typeparam> 5 /// <param name="obj">传入的对象</param> 6 /// <returns></returns> 7 public static T GetParentObject<T>(DependencyObject obj) where T : FrameworkElement 8 { 9 DependencyObject parent = VisualTreeHelper.GetParent(obj); 10 11 while (parent != null) 12 { 13 if (parent is T) 14 { 15 return (T)parent; 16 } 17 parent = VisualTreeHelper.GetParent(parent); 18 } 19 return null; 20 }
1 /// <summary> 2 /// 获取指定类型的可视子对象 3 /// </summary> 4 /// <typeparam name="T">指定类型</typeparam> 5 /// <param name="obj">传入的对象</param> 6 /// <returns></returns> 7 public static T GetChildObject<T>(DependencyObject obj) where T : FrameworkElement 8 { 9 DependencyObject child = null; 10 T grandChild = null; 11 12 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++) 13 { 14 child = VisualTreeHelper.GetChild(obj, i); 15 16 if (child is T) 17 { 18 return (T)child; 19 } 20 else 21 { 22 grandChild = GetChildObject<T>(child); 23 if (grandChild != null) 24 return grandChild; 25 } 26 } 27 return null; 28 }