Skip to content

Instantly share code, notes, and snippets.

@kolesnick
Last active February 23, 2018 06:48
Show Gist options
  • Save kolesnick/8cb46af724038e322707f24da8ea2d73 to your computer and use it in GitHub Desktop.
Save kolesnick/8cb46af724038e322707f24da8ea2d73 to your computer and use it in GitHub Desktop.
public static IEnumerable<TNode> UnfoldTree<TNode>(this TNode root, Func<TNode, IEnumerable<TNode>> getChildren)
{
var queue = new Queue<TNode>(new [] { root });
while (queue.Count > 0)
{
var node = queue.Dequeue();
yield return node;
foreach (var child in getChildren(node))
{
queue.Enqueue(child);
}
}
}
public static IEnumerable<DependencyObject> GetChildren(this DependencyObject node)
{
int childrenCount = VisualTreeHelper.GetChildrenCount(node);
for (int childIndex = 0; childIndex < childrenCount; childIndex++)
{
yield return VisualTreeHelper.GetChild(node, childIndex);
}
}
private static IEnumerable<DependencyObject> Descendants(DependencyObject node) =>
node
.UnfoldTree(GetChildren)
.Skip(1);
public static T FirstDescendantOfType<T>(this DependencyObject node) =>
Descendants(node)
.OfType<T>()
.First();
@kolesnick
Copy link
Author

Usage:
var listView = navigationView.FirstDescendantOfType<ListView>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment