123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- using System.Collections.Generic;
- using System.Windows;
- using System.Windows.Media;
-
- namespace XHZB.Desktop.Utils
- {
- internal class VTHelper
- {
- public static T FindChild<T>(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<T>(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<T> FindChilds<T>(DependencyObject parent, string childName)
- where T : DependencyObject
- {
- List<T> list = new List<T>();
- 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<T> findChildList = FindChilds<T>(child, childName);
- for (int j = 0; j < findChildList.Count; j++)
- {
- }
- list.AddRange(FindChilds<T>(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;
- }
-
- /// <summary>
- /// 查找父元素
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <param name="name"></param>
- /// <returns></returns>
- public static T FindParent<T>(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<T>(dobj);
- if (dobj != null && dobj is T)
- {
- return (T)dobj;
- }
- }
- }
- return null;
- }
- }
- }
|