Skip to content

Commit 4a74a5f

Browse files
committed
Added IsDescendantOf and IsAscendantOf APIs
1 parent f65ca87 commit 4a74a5f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Microsoft.Toolkit.Uwp.UI/Extensions/DependencyObjectExtensions.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,5 +695,42 @@ public static IEnumerable<DependencyObject> FindAscendants(this DependencyObject
695695
element = parent;
696696
}
697697
}
698+
699+
/// <summary>
700+
/// Checks whether or not a given <see cref="DependencyObject"/> instance is a descendant of another one.
701+
/// </summary>
702+
/// <param name="child">The input child element.</param>
703+
/// <param name="element">The element to look for in the ascendants hierarchy for <paramref name="child"/>.</param>
704+
/// <returns>Whether or not <paramref name="child"/> is a descendant of <paramref name="element"/>.</returns>
705+
public static bool IsDescendantOf(this DependencyObject child, DependencyObject element)
706+
{
707+
while (true)
708+
{
709+
DependencyObject? parent = VisualTreeHelper.GetParent(child);
710+
711+
if (parent is null)
712+
{
713+
return false;
714+
}
715+
716+
if (parent == element)
717+
{
718+
return true;
719+
}
720+
721+
child = parent;
722+
}
723+
}
724+
725+
/// <summary>
726+
/// Checks whether or not a given <see cref="DependencyObject"/> instance is an ascendant of another one.
727+
/// </summary>
728+
/// <param name="parent">The input parent element.</param>
729+
/// <param name="element">The element to look for in the descendants hierarchy for <paramref name="parent"/>.</param>
730+
/// <returns>Whether or not <paramref name="parent"/> is an ascendant of <paramref name="element"/>.</returns>
731+
public static bool IsAscendantOf(this DependencyObject parent, DependencyObject element)
732+
{
733+
return IsDescendantOf(element, parent);
734+
}
698735
}
699736
}

0 commit comments

Comments
 (0)