WPF VisualTreeHelper分析
Posted Ant-double
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF VisualTreeHelper分析相关的知识,希望对你有一定的参考价值。
1、方法一
public static int GetChildrenCount( DependencyObject reference )
可以看到接受任何为DependencyObject,wpf中的几乎所有的控件都继承自这个控件。
可以看到msdn上给的例子:
1 // Enumerate all the descendants of the visual object. 2 static public void EnumVisual(Visual myVisual) 3 { 4 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++) 5 { 6 // Retrieve child visual at specified index value. 7 Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i); 8 9 // Do processing of the child visual object. 10 11 // Enumerate children of the child visual object. 12 EnumVisual(childVisual); 13 } 14 }
下面是一封装的一个通用的方法
1 /// <summary> 2 /// 利用visualtreehelper寻找对象的子级对象 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="obj"></param> 6 /// <returns></returns> 7 List<T> FindVisualChild<T>(DependencyObject obj) where T : DependencyObject 8 { 9 try 10 { 11 List<T> TList = new List<T> { }; 12 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) 13 { 14 DependencyObject child = VisualTreeHelper.GetChild(obj, i); 15 if (child != null && child is T) 16 { 17 TList.Add((T)child); 18 } 19 else 20 { 21 List<T> childOfChildren = FindVisualChild<T>(child); 22 if (childOfChildren != null) 23 { 24 TList.AddRange(childOfChildren); 25 } 26 } 27 } 28 return TList; 29 } 30 catch (Exception ee) 31 { 32 MessageBox.Show(ee.Message); 33 return null; 34 } 35 }
二、
public static DependencyObject GetParent( DependencyObject reference )
可能看msdn上的例子:
1 /// <summary> 2 /// 利用VisualTreeHelper寻找指定依赖对象的父级对象 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="obj"></param> 6 /// <returns></returns> 7 public static List<T> FindVisualParent<T>(DependencyObject obj) where T : DependencyObject 8 { 9 try 10 { 11 List<T> TList = new List<T> { }; 12 DependencyObject parent = VisualTreeHelper.GetParent(obj); 13 if (parent != null && parent is T) 14 { 15 TList.Add((T)parent); 16 List<T> parentOfParent = FindVisualParent<T>(parent); 17 if (parentOfParent !=null) 18 { 19 TList.AddRange(parentOfParent); 20 } 21 } 22 else 23 { 24 25 } 26 return TList; 27 } 28 catch (Exception ee) 29 { 30 MessageBox.Show(ee.Message); 31 return null; 32 } 33 }
给出一个使用的例子:
1 private void btn_Two_Click(object sender, RoutedEventArgs e) 2 { 3 string parentName = ""; 4 List<Grid> gridList = FindVisualParent<Grid>(btn_Two); 5 foreach (Grid item in gridList) 6 { 7 parentName += string.IsNullOrEmpty(parentName) ? item.Name.ToString() : "," + item.Name.ToString(); 8 } 9 MessageBox.Show(string.Format(btn_Two.Name.ToString() + "共有{0}个逻辑父级,名称分别为{1}", gridList.Count, parentName)); 10 }
以上是关于WPF VisualTreeHelper分析的主要内容,如果未能解决你的问题,请参考以下文章
WPF ContextMenu+VisualTreeHelper实现删除控件操作