GetParentObject方法,获取父控件方法。该方法将根据当前控件,遍历查找其父控件是否存在。参数1是表示当前子控件名,参数2是要查询父控件名;使用VisualTreeHelper.GetParent方法获取当前父控件。
1 public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
2 {
3 DependencyObject parent = VisualTreeHelper.GetParent(obj);
4
5 while (parent != null)
6 {
7 if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
8 {
9 return (T)parent;
10 }
11
12 parent = VisualTreeHelper.GetParent(parent);
13 }
14
15 return null;
16 }
17
2 {
3 DependencyObject parent = VisualTreeHelper.GetParent(obj);
4
5 while (parent != null)
6 {
7 if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
8 {
9 return (T)parent;
10 }
11
12 parent = VisualTreeHelper.GetParent(parent);
13 }
14
15 return null;
16 }
17
另外一个Helper方法是GetChildObject,获取子控件方法。该方法将根据当前控件,遍历查找其子控件是否存在。参数1是表示当前父控件名,参数2是要查询子控件名;
1 public T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement
2 {
3 DependencyObject child = null;
4 T grandChild = null;
5
6 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
7 {
8 child = VisualTreeHelper.GetChild(obj, i);
9
10 if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
11 {
12 return (T)child;
13 }
14 else
15 {
16 grandChild = GetChildObject<T>(child, name);
17 if (grandChild != null)
18 return grandChild;
19 }
20 }
21
22 return null;
23
24 }
2 {
3 DependencyObject child = null;
4 T grandChild = null;
5
6 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
7 {
8 child = VisualTreeHelper.GetChild(obj, i);
9
10 if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
11 {
12 return (T)child;
13 }
14 else
15 {
16 grandChild = GetChildObject<T>(child, name);
17 if (grandChild != null)
18 return grandChild;
19 }
20 }
21
22 return null;
23
24 }
最后介绍一个Helper方法是GetChildObjects方法,该方法将把所有子控件作为List集合返回到客户端。其中第一个参数是父控件参数,而第二个参数是特定子控件名称,如果需要遍历全部子控件,第二个参数留空即可。
1 public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
2 {
3 DependencyObject child = null;
4 List<T> childList = new List<T>();
5
6 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
7 {
8 child = VisualTreeHelper.GetChild(obj, i);
9
10 if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
11 {
12 childList.Add((T)child);
13 }
14
15 childList.AddRange(GetChildObjects<T>(child,""));
16 }
17
18 return childList;
19
20 }
2 {
3 DependencyObject child = null;
4 List<T> childList = new List<T>();
5
6 for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
7 {
8 child = VisualTreeHelper.GetChild(obj, i);
9
10 if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
11 {
12 childList.Add((T)child);
13 }
14
15 childList.AddRange(GetChildObjects<T>(child,""));
16 }
17
18 return childList;
19
20 }