using System.Windows; using System.Windows.Media; namespace Bro.Common.ImageCanvas { public static class VisualTreeHelpers { /// /// Find first paretn of type T in VisualTree. /// public static T FindParentControl(this DependencyObject control) where T : DependencyObject { DependencyObject parent = VisualTreeHelper.GetParent(control); while (parent != null && !(parent is T)) parent = VisualTreeHelper.GetParent(parent); return parent as T; } /// /// Find first child of type T in VisualTree. /// public static T FindChildControl(this DependencyObject control) where T : DependencyObject { int childNumber = VisualTreeHelper.GetChildrenCount(control); for (var i = 0; i < childNumber;) { DependencyObject child = VisualTreeHelper.GetChild(control, i); return (child is T) ? (T)child : FindChildControl(child); } return null; } } }