原文:
【C#】wpf查找父子节点
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; namespace TestSeagate.Common { class UIAssociate { /// <summary> /// 查找第一个父节点是T类型的节点,并返回。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dobj"></param> /// <returns></returns> public static T GetAncestor<T>(DependencyObject dobj) where T : FrameworkElement { DependencyObject parent = VisualTreeHelper.GetParent(dobj);//可视树 深入内部 while (!(parent is T) && parent != null) { parent = VisualTreeHelper.GetParent(parent); } if (parent != null) { return (T)parent; } else { return null; } } /// <summary> /// 查找所有满足条件的子节点, /// </summary> /// <typeparam name="T"></typeparam> /// <param name="depen"></param> /// <param name="childname"></param> /// <returns></returns> public static List<T> GetChildren<T>(DependencyObject depen,string childname=null) where T:FrameworkElement { DependencyObject child = null; List<T> lists = new List<T>(); for(int i=0;i<VisualTreeHelper.GetChildrenCount(depen);i++) { child = VisualTreeHelper.GetChild(depen,i); if((child is T)&&(((T)child).Name==childname||string.IsNullOrEmpty(childname))) { lists.Add((T)child); } lists.AddRange(GetChildren<T>(child, childname)); } return lists; } } }