/// <summary> /// Finds a Child of a given item in the visual tree. /// </summary> /// <param name="parent">A direct parent of the queried item.</param> /// <typeparam name="T">The type of the queried item.</typeparam> /// <param name="childName">x:Name or Name of child. </param> /// <returns>The first parent item that matches the submitted type parameter. /// If not matching item can be found, /// a null parent is being returned.</returns> public static T ChildOfType <T>(this DependencyObject parent, string childName = null) where T : DependencyObject { // Confirm parent and childName are valid. if (parent == null) { return(null); } if (childName != null) { return(parent.ChildrenOfType <T>() .FirstOrDefault(x => { var xf = x as FrameworkElement; if (xf == null) { return false; } return xf.Name == childName; })); } return(parent.ChildrenOfType <T>().FirstOrDefault()); }
internal static T GetFirstDescendantOfType <T>(this DependencyObject target) where T : DependencyObject { var obj = target as T; if (obj != null) { return(obj); } return(target.ChildrenOfType <T>().FirstOrDefault()); }
/// <summary> /// Does a deep search of the element tree, trying to find a descendant of the given type /// (including the element itself). /// </summary> /// <returns>True if the target is one of the elements.</returns> internal static T GetFirstDescendantOfType <T>(this DependencyObject target) where T : DependencyObject { T t = (T)(target as T); if (t == null) { t = target.ChildrenOfType <T>().FirstOrDefault <T>(); } return(t); }
/// <summary> /// Does a deep search of the element tree, trying to find a descendant of the given type /// (including the element itself). /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The target<see cref="DependencyObject"/></param> /// <returns>True if the target is one of the elements.</returns> internal static T GetFirstDescendantOfType <T>(this DependencyObject target) where T : DependencyObject { return(target as T ?? target.ChildrenOfType <T>().FirstOrDefault()); }
/// <summary> /// The FindChildrenByType /// </summary> /// <typeparam name="T"></typeparam> /// <param name="element">The element<see cref="DependencyObject"/></param> /// <returns>The <see cref="IEnumerable{T}"/></returns> internal static IEnumerable <T> FindChildrenByType <T>(this DependencyObject element) where T : DependencyObject { return(element.ChildrenOfType <T>()); }
/// <summary> /// Finds child element of the specified type. Uses breadth-first search. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="element">The target <see cref="DependencyObject"/> which children will be traversed.</param> /// <returns>The first child element that is of the specified type.</returns> public static T FindChildByType <T>(this DependencyObject element) where T : DependencyObject { return(element.ChildrenOfType <T>().FirstOrDefault()); }