Skip to content

Commit a174c20

Browse files
committed
Added FindAscendantsOrSelf API
1 parent 488c705 commit a174c20

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

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

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -840,8 +840,8 @@ static IEnumerable<DependencyObject> ThrowArgumentOutOfRangeExceptionForInvalidS
840840
/// <para>
841841
/// This method is meant to provide extra flexibility in specific scenarios and it should not
842842
/// be used when only the first item is being looked for. In those cases, use one of the
843-
/// available <see cref="FindAscendant{T}(DependencyObject)"/> overloads instead, which will
844-
/// offer a more compact syntax as well as better performance in those cases.
843+
/// available <see cref="FindAscendant{T}(DependencyObject)"/> overloads instead,
844+
/// which will offer a more compact syntax as well as better performance in those cases.
845845
/// </para>
846846
/// </summary>
847847
/// <param name="element">The root element.</param>
@@ -863,6 +863,37 @@ public static IEnumerable<DependencyObject> FindAscendants(this DependencyObject
863863
}
864864
}
865865

866+
/// <summary>
867+
/// Find all ascendant elements of the specified element (or self). This method can be chained
868+
/// with LINQ calls to add additional filters or projections on top of the returned results.
869+
/// <para>
870+
/// This method is meant to provide extra flexibility in specific scenarios and it should not
871+
/// be used when only the first item is being looked for. In those cases, use one of the
872+
/// available <see cref="FindAscendantOrSelf{T}(DependencyObject)"/> overloads instead,
873+
/// which will offer a more compact syntax as well as better performance in those cases.
874+
/// </para>
875+
/// </summary>
876+
/// <param name="element">The root element.</param>
877+
/// <returns>All the descendant <see cref="DependencyObject"/> instance from <paramref name="element"/>.</returns>
878+
public static IEnumerable<DependencyObject> FindAscendantsOrSelf(this DependencyObject element)
879+
{
880+
yield return element;
881+
882+
while (true)
883+
{
884+
DependencyObject? parent = VisualTreeHelper.GetParent(element);
885+
886+
if (parent is null)
887+
{
888+
yield break;
889+
}
890+
891+
yield return parent;
892+
893+
element = parent;
894+
}
895+
}
896+
866897
/// <summary>
867898
/// Checks whether or not a given <see cref="DependencyObject"/> instance is a descendant of another one.
868899
/// </summary>

0 commit comments

Comments
 (0)