Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes Linq extension methods are what you are after but you need to put inplace a litte infrastructure first:-</p> <pre><code>public static class VisualTreeEnumeration { public static IEnumerable&lt;DependencyObject&gt; Descendents(this DependencyObject root, int depth) { int count = VisualTreeHelper.GetChildrenCount(root); for (int i = 0; i &lt; count; i++) { var child = VisualTreeHelper.GetChild(root, i); yield return child; if (depth &gt; 0) { foreach (var descendent in Descendents(child, --depth)) yield return descendent; } } } public static IEnumerable&lt;DependencyObject&gt; Descendents(this DependencyObject root) { return Descendents(root, Int32.MaxValue); } public static IEnumerable&lt;DependencyObject&gt; Ancestors(this DependencyObject root) { DependencyObject current = VisualTreeHelper.GetParent(root); while (current != null) { yield return current; current = VisualTreeHelper.GetParent(current); } } } </code></pre> <p>Now you can use Linq to query into the visual tree using Linq. Some examples:-</p> <pre><code> // Get all text boxes in usercontrol:- this.Descendents().OfType&lt;TextBox&gt;(); // All UIElement direct children of the layout root grid:- LayoutRoot.Descendents(0).OfType&lt;UIElement&gt;(); // Find the containing `ListBoxItem` for an element:- elem.Ancestors().OfType&lt;ListBoxItem&gt;.FirstOrDefault(); // Seek button with name "PinkElephants" even if outside of the current Namescope:- this.Descendents() .OfType&lt;Button&gt;() .FirstOrDefault(b =&gt; b.Name == "PinkElephants"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload