Last active
February 23, 2018 06:48
-
-
Save kolesnick/8cb46af724038e322707f24da8ea2d73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
var listView = navigationView.FirstDescendantOfType<ListView>();