using System.Windows; using System.Windows.Media; namespace Muchinfo.PC.Common.Helpers { public class WPFVisualTreeHelper { /// /// 从父容器中查找指定类型的控件 /// /// /// /// public static T FindVisualChild(DependencyObject parent) where T : DependencyObject { if (parent == null) return null; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var childObject = VisualTreeHelper.GetChild(parent, i); if (childObject == null) return null; var child = childObject as T; if (child == null) { var childItem = FindVisualChild(childObject); if (childItem != null) return childItem; } return child; } return null; } /// /// 查找指定类型的父容器 /// /// /// The child. /// ``0. public static T FindVisualParent(DependencyObject child) where T : DependencyObject { if (child == null) return null; var parentObject = VisualTreeHelper.GetParent(child); if (parentObject == null) return null; var parent = parentObject as T; return parent ?? FindVisualParent(parentObject); } ///// ///// Finds the child. ///// ///// ///// The node. ///// ``0. //public static T FindChild(DependencyObject node) // where T : DependencyObject //{ // if (node == null) return null; // T found = null; // var childlen = VisualTreeHelper.GetChildrenCount(node); // for (int i = 0; i < childlen; i++) // { // var child = VisualTreeHelper.GetChild(node, i); // var target = child as T; // if (target == null) // { // found = FindChild(child); // if (found != null) // break; // } // else // { // found = (T)child; // break; // } // } // return found; //} } }