#
查找指定类型的子控件
- /// <summary>
- /// Find Child with Visual Tree
- /// </summary>
- /// <typeparam name="T">specail type</typeparam>
- /// <param name="root">the element starts</param>
- /// <returns></returns>
- public static T FindChild<T>(DependencyObject root) where T : DependencyObject
- {
- if (root == null)
- return null;
- T founded = null;
- for (int j = 0; j < VisualTreeHelper.GetChildrenCount(root); j++)
- {
- DependencyObject d = VisualTreeHelper.GetChild(root, j);
- T childType = d as T;
- if (childType == null)
- {
- founded = FindChild<T>(d);
- if (founded != null)
- break;
- }
- else
- {
- founded = childType;
- break;
- }
- }
- return founded;
- }
////// Find Child with Visual Tree /// ///specail type /// the element starts ///public static T FindChild (DependencyObject root) where T : DependencyObject { if (root == null) return null; T founded = null; for (int j = 0; j < VisualTreeHelper.GetChildrenCount(root); j++) { DependencyObject d = VisualTreeHelper.GetChild(root, j); T childType = d as T; if (childType == null) { founded = FindChild (d); if (founded != null) break; } else { founded = childType; break; } } return founded; }
查找指定类型指定名称的子控件:
- /// <summary>
- /// Find Child with Visual Tree
- /// </summary>
- /// <typeparam name="T">specail type</typeparam>
- /// <param name="root">the element starts</param>
- /// <returns></returns>
- public static T FindChild<T>(DependencyObject root, string name) where T : DependencyObject
- {
- if (root == null)
- return null;
- T founded = null;
- for (int j = 0; j < VisualTreeHelper.GetChildrenCount(root); j++)
- {
- DependencyObject d = VisualTreeHelper.GetChild(root, j);
- T childType = d as T;
- if (childType == null || ((d is FrameworkElement) && (d as FrameworkElement).Name != name))
- {
- founded = FindChild<T>(d, name);
- if (founded != null)
- break;
- }
- else
- {
- founded = childType;
- break;
- }
- }
- return founded;
- }
////// Find Child with Visual Tree /// ///specail type /// the element starts ///public static T FindChild (DependencyObject root, string name) where T : DependencyObject { if (root == null) return null; T founded = null; for (int j = 0; j < VisualTreeHelper.GetChildrenCount(root); j++) { DependencyObject d = VisualTreeHelper.GetChild(root, j); T childType = d as T; if (childType == null || ((d is FrameworkElement) && (d as FrameworkElement).Name != name)) { founded = FindChild (d, name); if (founded != null) break; } else { founded = childType; break; } } return founded; }
查找父控件:
- public static T FindParent<T>(DependencyObject d) where T : DependencyObject
- {
- DependencyObject parent = d;
- while (parent != null)
- {
- parent = VisualTreeHelper.GetParent(parent);
- if (parent != null && (parent.GetType() == typeof(T)))
- {
- return parent as T;
- }
- }
- return parent as T;
- }