重构到扩展方法(4):轻松遍历WPF可视树与逻辑树
public static class VisualExtension { public static T FindAncestor<T>(this DependencyObject dependencyObject) where T : class { while (dependencyObject != null && !(dependencyObject is T)) { dependencyObject = VisualTreeHelper.GetParent(dependencyObject); } return dependencyObject as T; } public static T FindAncestor<T>(this Visual visual) where T : Visual { while (visual != null && !(visual is T)) { visual = (Visual)VisualTreeHelper.GetParent(visual); } return (T)visual; } public static T FindAncestor<T>(this Visual visual, Predicate<T> predicate) where T : Visual { while (visual != null && !predicate(visual as T)) { visual = (Visual)VisualTreeHelper.GetParent(visual); } return (T)visual; } public static T FindAncestorByLogicalTree<T>(this Visual visual) where T : Visual { while (visual != null && !(visual is T)) { visual = (Visual)LogicalTreeHelper.GetParent(visual); } return (T)visual; } public static T FindVisualChild<T>(this DependencyObject obj) where T : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is T) return (T)child; else { T childOfChild = child.FindVisualChild<T>(); if (childOfChild != null) return childOfChild; } } return null; } }