using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace XHZB.Desktop.Utils { internal class VTHelper { public static T FindChild(DependencyObject parent, string childName) where T : DependencyObject { if (parent == null) { return null; } T foundChild = null; int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); // 如果子控件不是需查找的控件类型 T childType = child as T; if (childType == null) { // 在下一级控件中递归查找 foundChild = FindChild(child, childName); // 找到控件就可以中断递归操作 if (foundChild != null) { break; } } else if (!string.IsNullOrEmpty(childName)) { FrameworkElement frameworkElement = child as FrameworkElement; // 如果控件名称符合参数条件 if (frameworkElement != null && frameworkElement.Name == childName) { foundChild = (T)child; break; } } else { // 查找到了控件 foundChild = (T)child; break; } } return foundChild; } public static List FindChilds(DependencyObject parent, string childName) where T : DependencyObject { List list = new List(); if (parent == null) { return list; } int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); // 如果子控件不是需查找的控件类型 T childType = child as T; if (childType == null) { // 在下一级控件中递归查找 List findChildList = FindChilds(child, childName); for (int j = 0; j < findChildList.Count; j++) { } list.AddRange(FindChilds(child, childName)); } else if (!string.IsNullOrEmpty(childName)) { FrameworkElement frameworkElement = child as FrameworkElement; // 如果控件名称符合参数条件 if (frameworkElement != null && frameworkElement.Name == childName) { list.Add((T)child); } } else { // 查找到了控件 list.Add((T)child); } } return list; } /// /// 查找父元素 /// /// /// /// /// public static T FindParent(DependencyObject i_dp) where T : DependencyObject { DependencyObject dobj = VisualTreeHelper.GetParent(i_dp); if (dobj != null) { if (dobj is T) { return (T)dobj; } else { dobj = FindParent(dobj); if (dobj != null && dobj is T) { return (T)dobj; } } } return null; } } }