<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Colin Eberhardt&#039;s Adventures in .NET &#187; linq</title>
	<atom:link href="http://www.scottlogic.co.uk/blog/colin/tag/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.scottlogic.co.uk/blog/colin</link>
	<description>Colin Eberhardt&#039;s Adventures in .NET</description>
	<lastBuildDate>Thu, 09 Feb 2012 10:21:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Linq to Visual Tree</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 13:45:51 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[codeproject]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[t4]]></category>
		<category><![CDATA[templates]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=588</guid>
		<description><![CDATA[This blog post demonstrates a Linq API which can be used to query the WPF / Silverlight Visual Tree. You can find a few other Linq to Visual Tree techniques on other blogs, but what makes this one unique is that it retains, and allows queries that make use of the tree like structure rather [...]]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Fwww.scottlogic.co.uk%252Fblog%252Fcolin%252F2010%252F03%252Flinq-to-visual-tree%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Linq%20to%20Visual%20Tree%20%23%22%20%7D);"></div>
<p><em>This blog post demonstrates a Linq API which can be used to query the WPF / Silverlight Visual Tree. You can find a few other Linq to Visual Tree techniques on other blogs, but what makes this one unique is that it retains, and allows queries that make use of the tree like structure rather than simply flattening it.</em></p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/tree-300x92.jpg" alt="" title="tree" width="300" height="92" class="aligncenter size-medium wp-image-608" /></p>
<p>I have recently published an article on codeproject which describes a technique for <a href="http://www.codeproject.com/KB/linq/LinqToTree.aspx">generating Linq API for querying tree-like structures</a>. This blog post makes use of a generated API for WPF / Silverlight. If you are interested in the more generic approach, and how this API was constructed, (and how it is influenced by XPath) head on over to codeproject &#8230;</p>
<p>What I will provide here is a brief overview of the Linq to Visual Tree API. The full sourcecode for this API is at the end of this article.</p>
<p>The Linq to Visual Tree API defines a number of extension methods on <code>DependencyObject</code> that provide mechanisms for navigating to other <code>DependencyObject</code> instances. I will provide a few examples that query the following simple markup:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;GridOne&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxOne&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;One&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;StackPanelOne&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxTwo&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Two&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;GridTwo&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxThree&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Three&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;StackPanelTwo&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxFour&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Four&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>                    
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>We&#8217;ll start with a simple  example. Include the Linq to Visual Tree namespace, then use the Descendants method to obtain all the descendants (i.e. children and children&#8217;s children, etc &#8230;) of an object within the<br />
visual tree.</p>
<p><strong>Descendants</strong></p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/descendants.png" alt="" title="descendants" width="200" height="117" class="aligncenter size-full wp-image-598" /></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">LinqToVisualTree</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// all items within the visual tree</span>
IEnumerable<span style="color: #008000;">&lt;</span>DependencyObject<span style="color: #008000;">&gt;</span> allDescendants <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
gives ...
0 {Grid} 	[GridOne]
1 {TextBox} 	[TextBoxOne]
2 {StackPanel} 	[StackPanelOne]
3 {TextBox} 	[TextBoxTwo]
4 {Grid} 	[GridTwo]
5 {TextBox} 	[TextBoxThree]
6 {StackPanel} 	[StackPanelTwo]
7 {TextBox} 	[TextBoxFour]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// all items within the visual tree of 'GridTwo'</span>
var descendantsOfGridTwo <span style="color: #008000;">=</span> GridTwo<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
gives ...
0 {TextBox} 	[TextBoxThree]
1 {StackPanel} 	[StackPanelTwo]
2 {TextBox} 	[TextBoxFour]
*/</span></pre></div></div>

<p>Each of the extension methods also has a corresponding method with a generic type parameter that filters the collection to find elements of a specific type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// all items within the visual tree of 'GridTwo' that are textboxes</span>
var textBoxDescendantsOfGridTwo <span style="color: #008000;">=</span> GridTwo<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                                         <span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i <span style="color: #008000;">is</span> TextBox<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxThree]
1 {TextBox} 	[TextBoxFour]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// a shorthand using the generic version of Descendants</span>
var textBoxDescendantsOfGridTwo2 <span style="color: #008000;">=</span> GridTwo<span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>TextBox<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxThree]
1 {TextBox} 	[TextBoxFour]
*/</span></pre></div></div>

<p><strong>Elements</strong></p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/child.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/child.png" alt="" title="child" width="200" height="117" class="aligncenter size-full wp-image-597" /></a></p>
<p>The elements extension method obtains all the direct children of an item in the visual tree:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// find all direct children of this user control </span>
var userControlChildren <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Elements</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {Grid} 	[GridOne]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// find all direct children of the grid 'GridTwo'</span>
var gridChildren <span style="color: #008000;">=</span> GridTwo<span style="color: #008000;">.</span><span style="color: #0000FF;">Elements</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxThree]
1 {StackPanel} 	[StackPanelTwo]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// find all direct children of the grid 'GridTwo' that are StackPanels</span>
var gridChildren2 <span style="color: #008000;">=</span> GridTwo<span style="color: #008000;">.</span><span style="color: #0000FF;">Elements</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
*/</span></pre></div></div>

<p>There are also, <code>ElementsBeforeSelf</code> and <code>ElementsAfterSelf</code> methods that return the elements before and after the item which the method is being invoked upon.</p>
<p><strong>Ancestors</strong></p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/ancestors.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/ancestors.png" alt="" title="ancestors" width="200" height="117" class="aligncenter size-full wp-image-599" /></a></p>
<p>The ancestors methods traverse the tree towards the root, finding all the ancestors:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// the ancestors for 'TextBoxFour'</span>
var ancestors <span style="color: #008000;">=</span> TextBoxFour<span style="color: #008000;">.</span><span style="color: #0000FF;">Ancestors</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
1 {Grid} 	[GridTwo]
2 {StackPanel} 	[StackPanelOne]
3 {Grid} 	[GridOne]
4 {MainPage} 	[]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// the ancestors for 'TextBoxFour' that are StackPanels</span>
var stackPanelAncestors <span style="color: #008000;">=</span> TextBoxFour<span style="color: #008000;">.</span><span style="color: #0000FF;">Ancestors</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
1 {StackPanel} 	[StackPanelOne]
*/</span></pre></div></div>

<p><strong>Putting it all together</strong></p>
<p>The Linq to Tree API not only defines extension methods on <code>DependencyObject</code>, but also the same extension methods on <code>IEnumerable&lt;DependencyObject&gt;</code>. Unless you have previous experience of Linq to XML, I would strongly suggest reading my <a href="http://www.codeproject.com/KB/linq/LinqToTree.aspx">codeproject article</a> to understand how this works! </p>
<p>This allows you to form much more complex queries. For example, you can find all <code>TextBox</code>s that have a <code>Grid</code> as a direct parent:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var itemsFluent <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>TextBox<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                      <span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i<span style="color: #008000;">.</span><span style="color: #0000FF;">Ancestors</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FirstOrDefault</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">is</span> Grid<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var itemsQuery <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">from</span> v <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>TextBox<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                 <span style="color: #0600FF; font-weight: bold;">where</span> v<span style="color: #008000;">.</span><span style="color: #0000FF;">Ancestors</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FirstOrDefault</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">is</span> Grid
                 <span style="color: #0600FF; font-weight: bold;">select</span> v<span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxOne]
1 {TextBox} 	[TextBoxThree]
*/</span></pre></div></div>

<p>Here, you can also see we are mixing the fluent and query syntax for Linq. Both give the same result.</p>
<p>The next example finds all <code>StackPanel</code>s that are within another <code>StackPanel</code>s visual tree:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var items2Fluent <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                              <span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var items2Query <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">from</span> i <span style="color: #0600FF; font-weight: bold;">in</span>
                      <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">from</span> v <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                       <span style="color: #0600FF; font-weight: bold;">select</span> v<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                  <span style="color: #0600FF; font-weight: bold;">select</span> i<span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
*/</span></pre></div></div>

<p>Finally, this one-liner, outputs the entire visual tree in ASCII! It makes use of the <code>DescendantsAndSelf</code>, <code>Ancestors</code> and <code>ElementsBeforeSelf</code> methods, plus the funky Linq <code>Aggregate</code> method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> tree <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DescendantsAndSelf</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Aggregate</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span>,
    <span style="color: #008000;">&#40;</span>bc, n<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> bc <span style="color: #008000;">+</span> n<span style="color: #008000;">.</span><span style="color: #0000FF;">Ancestors</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Aggregate</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span>, <span style="color: #008000;">&#40;</span>ac, m<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#40;</span>m<span style="color: #008000;">.</span><span style="color: #0000FF;">ElementsAfterSelf</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Any</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;| &quot;</span> <span style="color: #008000;">:</span> <span style="color: #666666;">&quot;  &quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> ac,
    ac <span style="color: #008000;">=&gt;</span> ac <span style="color: #008000;">+</span> <span style="color: #008000;">&#40;</span>n<span style="color: #008000;">.</span><span style="color: #0000FF;">ElementsAfterSelf</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Any</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;+-&quot;</span> <span style="color: #008000;">:</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\\</span>-&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> n<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<pre>
\-MainPage
  \-Grid
    +-TextBox
    | \-Grid
    |   +-Border
    |   | \-Grid
    |   |   +-Border
    |   |   \-Border
    |   |     \-ScrollViewer
    |   |       \-Border
    |   |         \-Grid
    |   |           +-ScrollContentPresenter
    |   |           | \-TextBoxView
    |   |           +-Rectangle
    |   |           +-ScrollBar
    |   |           \-ScrollBar
    |   +-Border
    |   +-Border
    |   \-Border
    |     \-Grid
    |       +-Path
    |       \-Path
    \-StackPanel
      +-TextBox
      | \-Grid
      |   +-Border
      |   | \-Grid
      |   |   +-Border
      |   |   \-Border
      |   |     \-ScrollViewer
      |   |       \-Border
      |   |         \-Grid
      |   |           +-ScrollContentPresenter
      |   |           | \-TextBoxView
      |   |           +-Rectangle
      |   |           +-ScrollBar
      |   |           \-ScrollBar
      |   +-Border
      |   +-Border
      |   \-Border
      |     \-Grid
      |       +-Path
      |       \-Path
      \-Grid
        +-TextBox
        | \-Grid
        |   +-Border
        |   | \-Grid
        |   |   +-Border
        |   |   \-Border
        |   |     \-ScrollViewer
        |   |       \-Border
        |   |         \-Grid
        |   |           +-ScrollContentPresenter
        |   |           | \-TextBoxView
        |   |           +-Rectangle
        |   |           +-ScrollBar
        |   |           \-ScrollBar
        |   +-Border
        |   +-Border
        |   \-Border
        |     \-Grid
        |       +-Path
        |       \-Path
        \-StackPanel
          \-TextBox
            \-Grid
              +-Border
              | \-Grid
              |   +-Border
              |   \-Border
              |     \-ScrollViewer
              |       \-Border
              |         \-Grid
              |           +-ScrollContentPresenter
              |           | \-TextBoxView
              |           +-Rectangle
              |           +-ScrollBar
              |           \-ScrollBar
              +-Border
              +-Border
              \-Border
                \-Grid
                  +-Path
                  \-Path
</pre>
<p>Note: this was invoked after the <code>LayoutUpdated</code> event so that we not only see the elements from our XAML, but also the elements created from their templates, giving us our full run-time visual tree.</p>
<p>You can download a simple Silverlight application that demonstrated all the examples given above:<br />
<a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/LinqToTree.zip'>LinqToTree.zip</a>. </p>
<p>Or, if you just want the Linq to VisualTree code, you can copy-n-paste from the windows below which has the entire API, which includes the methods illustrated above, plus their <code>IEnumerable</code> equivalents, and a few others I have not illustrated.</p>
<pre style="height: 350px; overflow: scroll; border: 1px solid #aaa;">
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace LinqToVisualTree
{
    /// &lt;summary&gt;
    /// Adapts a DependencyObject to provide methods required for generate
    /// a Linq To Tree API
    /// &lt;/summary&gt;
    public class VisualTreeAdapter : ILinqTree&lt;DependencyObject&gt;
    {
        private DependencyObject _item;

        public VisualTreeAdapter(DependencyObject item)
        {
            _item = item;
        }

        public IEnumerable&lt;DependencyObject&gt; Children()
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(_item);
            for (int i = 0; i &lt; childrenCount; i++)
            {
                yield return VisualTreeHelper.GetChild(_item, i);
            }
        }

        public DependencyObject Parent
        {
            get
            {
                return VisualTreeHelper.GetParent(_item);
            }
        }
    }
}

namespace LinqToVisualTree
{
    /// &lt;summary&gt;
    /// Defines an interface that must be implemented to generate the LinqToTree methods
    /// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
    public interface ILinqTree&lt;T&gt;
    {
        IEnumerable&lt;T&gt; Children();

        T Parent { get; }
    }

    public static class TreeExtensions
    {
        /// &lt;summary&gt;
        /// Returns a collection of descendant elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Descendants(this DependencyObject item)
        {
            ILinqTree&lt;DependencyObject&gt; adapter = new VisualTreeAdapter(item);
            foreach (var child in adapter.Children())
            {
                yield return child;

                foreach (var grandChild in child.Descendants())
                {
                    yield return grandChild;
                }
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all descendant elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; DescendantsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var child in item.Descendants())
            {
                yield return child;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection of ancestor elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Ancestors(this DependencyObject item)
        {
            ILinqTree&lt;DependencyObject&gt; adapter = new VisualTreeAdapter(item);

            var parent = adapter.Parent;
            while (parent != null)
            {
                yield return parent;
                adapter = new VisualTreeAdapter(parent);
                parent = adapter.Parent;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all ancestor elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; AncestorsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var ancestor in item.Ancestors())
            {
                yield return ancestor;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection of child elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Elements(this DependencyObject item)
        {
            ILinqTree&lt;DependencyObject&gt; adapter = new VisualTreeAdapter(item);
            foreach (var child in adapter.Children())
            {
                yield return child;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection of the sibling elements before this node, in document order.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsBeforeSelf(this DependencyObject item)
        {
            if (item.Ancestors().FirstOrDefault() == null)
                yield break;
            foreach (var child in item.Ancestors().First().Elements())
            {
                if (child.Equals(item))
                    break;
                yield return child;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection of the after elements after this node, in document order.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsAfterSelf(this DependencyObject item)
        {
            if (item.Ancestors().FirstOrDefault() == null)
                yield break;
            bool afterSelf = false;
            foreach (var child in item.Ancestors().First().Elements())
            {
                if (afterSelf)
                    yield return child;

                if (child.Equals(item))
                    afterSelf = true;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all child elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var child in item.Elements())
            {
                yield return child;
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection of descendant elements which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Descendants&lt;T&gt;(this DependencyObject item)
        {
            return item.Descendants().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection of the sibling elements before this node, in document order
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsBeforeSelf&lt;T&gt;(this DependencyObject item)
        {
            return item.ElementsBeforeSelf().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection of the after elements after this node, in document order
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsAfterSelf&lt;T&gt;(this DependencyObject item)
        {
            return item.ElementsAfterSelf().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all descendant elements
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; DescendantsAndSelf&lt;T&gt;(this DependencyObject item)
        {
            return item.DescendantsAndSelf().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection of ancestor elements which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Ancestors&lt;T&gt;(this DependencyObject item)
        {
            return item.Ancestors().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all ancestor elements
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; AncestorsAndSelf&lt;T&gt;(this DependencyObject item)
        {
            return item.AncestorsAndSelf().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection of child elements which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Elements&lt;T&gt;(this DependencyObject item)
        {
            return item.Elements().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all child elements.
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsAndSelf&lt;T&gt;(this DependencyObject item)
        {
            return item.ElementsAndSelf().Where(i =&gt; i is T).Cast&lt;DependencyObject&gt;();
        }

    }

    public static class EnumerableTreeExtensions
    {
        /// &lt;summary&gt;
        /// Applies the given function to each of the items in the supplied
        /// IEnumerable.
        /// &lt;/summary&gt;
        private static IEnumerable&lt;DependencyObject&gt; DrillDown(this IEnumerable&lt;DependencyObject&gt; items,
            Func&lt;DependencyObject, IEnumerable&lt;DependencyObject&gt;&gt; function)
        {
            foreach (var item in items)
            {
                foreach (var itemChild in function(item))
                {
                    yield return itemChild;
                }
            }
        }

        /// &lt;summary&gt;
        /// Applies the given function to each of the items in the supplied
        /// IEnumerable, which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; DrillDown&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items,
            Func&lt;DependencyObject, IEnumerable&lt;DependencyObject&gt;&gt; function)
            where T : DependencyObject
        {
            foreach (var item in items)
            {
                foreach (var itemChild in function(item))
                {
                    if (itemChild is T)
                    {
                        yield return (T)itemChild;
                    }
                }
            }
        }

        /// &lt;summary&gt;
        /// Returns a collection of descendant elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Descendants(this IEnumerable&lt;DependencyObject&gt; items)
        {
            return items.DrillDown(i =&gt; i.Descendants());
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all descendant elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; DescendantsAndSelf(this IEnumerable&lt;DependencyObject&gt; items)
        {
            return items.DrillDown(i =&gt; i.DescendantsAndSelf());
        }

        /// &lt;summary&gt;
        /// Returns a collection of ancestor elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Ancestors(this IEnumerable&lt;DependencyObject&gt; items)
        {
            return items.DrillDown(i =&gt; i.Ancestors());
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all ancestor elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; AncestorsAndSelf(this IEnumerable&lt;DependencyObject&gt; items)
        {
            return items.DrillDown(i =&gt; i.AncestorsAndSelf());
        }

        /// &lt;summary&gt;
        /// Returns a collection of child elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Elements(this IEnumerable&lt;DependencyObject&gt; items)
        {
            return items.DrillDown(i =&gt; i.Elements());
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all child elements.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsAndSelf(this IEnumerable&lt;DependencyObject&gt; items)
        {
            return items.DrillDown(i =&gt; i.ElementsAndSelf());
        }

        /// &lt;summary&gt;
        /// Returns a collection of descendant elements which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Descendants&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items)
            where T : DependencyObject
        {
            return items.DrillDown&lt;T&gt;(i =&gt; i.Descendants());
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all descendant elements.
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; DescendantsAndSelf&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items)
            where T : DependencyObject
        {
            return items.DrillDown&lt;T&gt;(i =&gt; i.DescendantsAndSelf());
        }

        /// &lt;summary&gt;
        /// Returns a collection of ancestor elements which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Ancestors&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items)
            where T : DependencyObject
        {
            return items.DrillDown&lt;T&gt;(i =&gt; i.Ancestors());
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all ancestor elements.
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; AncestorsAndSelf&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items)
            where T : DependencyObject
        {
            return items.DrillDown&lt;T&gt;(i =&gt; i.AncestorsAndSelf());
        }

        /// &lt;summary&gt;
        /// Returns a collection of child elements which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; Elements&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items)
            where T : DependencyObject
        {
            return items.DrillDown&lt;T&gt;(i =&gt; i.Elements());
        }

        /// &lt;summary&gt;
        /// Returns a collection containing this element and all child elements.
        /// which match the given type.
        /// &lt;/summary&gt;
        public static IEnumerable&lt;DependencyObject&gt; ElementsAndSelf&lt;T&gt;(this IEnumerable&lt;DependencyObject&gt; items)
            where T : DependencyObject
        {
            return items.DrillDown&lt;T&gt;(i =&gt; i.ElementsAndSelf());
        }
    }
}</pre>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
	</channel>
</rss>

