<?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; t4</title>
	<atom:link href="http://www.scottlogic.co.uk/blog/colin/tag/t4/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>ViewModel INotifyPropertyChanged Code Generation</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2011/04/viewmodel-inotifypropertychanged-code-generation/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2011/04/viewmodel-inotifypropertychanged-code-generation/#comments</comments>
		<pubDate>Thu, 21 Apr 2011 12:34:16 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code generation]]></category>
		<category><![CDATA[codeproject]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=1399</guid>
		<description><![CDATA[This blog post describes a novel method of generating boiler-plate MVVM code using codesnippet automation. You simply add attributes to your view model classes and the code is generated for you! Model-View-ViewModel (MVVM) has become the de facto pattern for Silverlight, WPF and WP7 applications, providing code that is easily tested and couples cleanly to [...]]]></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%252F2011%252F04%252Fviewmodel-inotifypropertychanged-code-generation%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22ViewModel%20INotifyPropertyChanged%20Code%20Generation%20%23%22%20%7D);"></div>
<p><i>This blog post describes a novel method of generating boiler-plate MVVM code using codesnippet automation. You simply add attributes to your view model classes and the code is generated for you!</i></p>
<p>Model-View-ViewModel (MVVM) has become the de facto pattern for Silverlight, WPF and WP7 applications, providing code that is easily tested and couples cleanly to the view via databinding. However, one small problem with MVVM is that it relies on the <code>INotifyPropertyChanged</code> (INPC) interface and the boiler-plate code which this entails.</p>
<p>This blog post describes a technique for implementing INPC and adding properties to your view model as easily as this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>SnippetINotifyPropertyChanged<span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>SnippetPropertyINPC<span style="color: #008000;">&#40;</span>field <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;_surname&quot;</span>, type <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;string&quot;</span>, property <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>SnippetPropertyINPC<span style="color: #008000;">&#40;</span>field <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;_forename&quot;</span>, type <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;string&quot;</span>, property <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Forename&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> PersonViewModel <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>There are hundreds of blog posts that describe solutions to the problem of implementing INPC including simple options like a <a href="http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/">base-class that implements the INPC interface</a>, the popular approach of using <a href=" http://10rem.net/blog/2010/12/16/strategies-for-improving-inotifypropertychanged-in-wpf-and-silverlight">lambda expressions</a> and more complex solutions involving <a href="http://justinangel.net/AutomagicallyImplementingINotifyPropertyChanged">Intermediate Language Weaving</a> (AOP), or <a href="http://www.deanchalk.me.uk/post/WPF-e28093-Easy-INotifyPropertyChanged-Via-DynamicObject-Proxy.aspx">dynamic proxies</a>.  However, for the sake of simplicity, most of the projects I have worked on have opted for a manual approach &#8211; with individual developers using <a href="http://geekswithblogs.net/brians/archive/2010/07/27/inotifypropertychanged-with-less-typing-using-a-code-snippet.aspx">codesnippets</a> if they so wish.</p>
<p>There are a couple of problems with codesnippets, firstly they are not refactor friendly, secondly they do not reduce boiler-plate code, they simply provide a method for adding this code more quickly!</p>
<p>Yesterday I published an article on codeproject which <a href="http://www.codeproject.com/KB/codegen/CodeSnippetAutomation.aspx">describes a technique for &#8216;automating&#8217; code snippets</a>, where you indicate the use of a codesnippet declaratively via an attribute, with the resultant code being generated in a partial class. Here I am going to show how it can be used to streamline the creation of ViewModels and results in the removal of boiler-plate code.</p>
<p>The first step to using this technique is to add the CodeGen folder to your project. This folder includes a number of T4 templates (Visual Studio&#8217;s built in code-generation framework):</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2011/04/AddCodeGen.png" alt="" title="AddCodeGen" width="344" height="379" class="aligncenter size-full wp-image-1417" /></p>
<p>With these templates added to your project, if you add a codesnippet to the project (i.e. a <code>.snippet</code> file), a corresponding attribute will be generated when the T4 templates are run. You can see in the above screenshot that a couple of snippets have been added and attributes generated. </p>
<p>The T4 templates are run when the project is built, or can be run on-demand by clicking the button indicated below:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2011/04/TransformAllTemplates.png" alt="" title="TransformAllTemplates" width="302" height="154" class="aligncenter size-full wp-image-1414" /></p>
<p>So let&#8217;s have a go at generating our view model code &#8230;</p>
<p>We&#8217;ll create a simple Person view model, which has properties of Surname, Forename and a dependent property of FullName which concatenates the two together. We&#8217;ll start by adding the INPC implementation to our class via an automated snippet:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>SnippetINotifyPropertyChanged<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> PersonViewModel <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>By adding the attribute above and compiling the code, you will find that a generated counterpart to our view model is created:</p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2011/04/GeneratedViewModel.png" alt="" title="GeneratedViewModel" width="346" height="227" class="aligncenter size-full wp-image-1416" /></p>
<p>This file contains the code defined in our INPC codesnippet:</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;">System.ComponentModel</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ViewModelCodeGeneration
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> PersonViewModel
  <span style="color: #008000;">&#123;</span>
&nbsp;
    <span style="color: #008080;">#region INotifyPropertyChanged Members</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Occurs when a property changes</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> PropertyChangedEventHandler PropertyChanged<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Raises a PropertyChanged event</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> property<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>PropertyChanged <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        PropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <span style="color: #008000;">new</span> PropertyChangedEventArgs<span style="color: #008000;">&#40;</span>property<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080;">#endregion</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We can now add a property to our view model:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>SnippetINotifyPropertyChanged<span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>SnippetPropertyINPC<span style="color: #008000;">&#40;</span>field <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;_surname&quot;</span>, type <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;string&quot;</span>, property <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> PersonViewModel <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Compiling the code and inspecting the generated file, we can see that the code has been generated based on the codesnippet that adds a property (with INPC <code>PropertyChanged</code>), based on the attribute parameters supplied above:</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;">System.ComponentModel</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ViewModelCodeGeneration
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> PersonViewModel
  <span style="color: #008000;">&#123;</span>
&nbsp;
    <span style="color: #008080;">#region INotifyPropertyChanged Members</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Occurs when a property changes</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> PropertyChangedEventHandler PropertyChanged<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Raises a PropertyChanged event</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> property<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>PropertyChanged <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        PropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <span style="color: #008000;">new</span> PropertyChangedEventArgs<span style="color: #008000;">&#40;</span>property<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080;">#endregion</span>
&nbsp;
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Field which backs the Surname property</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> _surname <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">string</span> SurnameProperty <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets / sets the Surname value</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Surname
    <span style="color: #008000;">&#123;</span>
      get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _surname<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
      set
      <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_surname <span style="color: #008000;">==</span> value<span style="color: #008000;">&#41;</span>
          <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span>
&nbsp;
        _surname <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
&nbsp;
        OnSurnameChanged<span style="color: #008000;">&#40;</span>value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        OnPropertyChanged<span style="color: #008000;">&#40;</span>SurnameProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Invoked when the value of Surname changes</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnSurnameChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Finally, we add the second property, and add implementations for the partial methods that are invoked when either <code>Surname</code> or <code>Forename</code> changes, allowing us to implement <code>FullName</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>SnippetINotifyPropertyChanged<span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>SnippetPropertyINPC<span style="color: #008000;">&#40;</span>field <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;_surname&quot;</span>, type <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;string&quot;</span>, property <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>SnippetPropertyINPC<span style="color: #008000;">&#40;</span>field <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;_forename&quot;</span>, type <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;string&quot;</span>, property <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Forename&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> PersonViewModel <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">string</span> FullNameProperty <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;FullName&quot;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnForenameChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> value<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    OnPropertyChanged<span style="color: #008000;">&#40;</span>FullNameProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnSurnameChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> value<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    OnPropertyChanged<span style="color: #008000;">&#40;</span>FullNameProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> FullName
  <span style="color: #008000;">&#123;</span>
    get
    <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> Surname <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;, &quot;</span> <span style="color: #008000;">+</span> Forename<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>All that&#8217;s left to do is bind our view model to the view:</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;Border</span> <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;DarkGray&quot;</span> <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;4&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">CornerRadius</span>=<span style="color: #ff0000;">&quot;3&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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</span> <span style="color: #000066;">l:GridUtils.ColumnDefinitions</span>=<span style="color: #ff0000;">&quot;*,*&quot;</span></span>
<span style="color: #009900;">          <span style="color: #000066;">l:GridUtils.RowDefinitions</span>=<span style="color: #ff0000;">&quot;Auto,Auto,&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;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding FullName}&quot;</span> <span style="color: #000066;">FontWeight</span>=<span style="color: #ff0000;">&quot;Bold&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">Grid.ColumnSpan</span>=<span style="color: #ff0000;">&quot;2&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;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Surname:&quot;</span></span>
<span style="color: #009900;">                <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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Surname, Mode=TwoWay}&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&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>  
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Forename:&quot;</span></span>
<span style="color: #009900;">                <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;2&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;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Forename, Mode=TwoWay}&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">Grid.Column</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;2&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 style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>(Note the <a href="http://www.scottlogic.co.uk/blog/colin/2010/12/a-simplified-grid-markup-for-silverlight-and-wpf/">simplified grid markup</a>!)</p>
<p>Here&#8217;s the code for this very simple example in action:</p>
<div style="text-align: center;"><object width="250" height="100" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2011/04/ViewModelCodeGeneration.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>This blog post has described a method for generating the boiler-plate code that the MVVM patterns requires. The use of T4 templates and partial classes mirrors the way that the Visual Studio designer generates code. Personally I think the end result is much easier to understand that the dynamic proxy or aspects / weaving approach described by others. The example given in this blog post is pretty trivial, but when you use it for bigger projects with complex view-models containing numerous properties, you really start to feel the benefit.</p>
<p>Furthermore, the technique described here can be used to automate any codesnippet! you can use it to generate dependency properties for example.</p>
<p>Enjoy!</p>
<p>You can download the sourcecode here: <a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2011/04/ViewModelGeneration.zip">ViewModelGeneration.zip</a></p>
<p>For more information regarding how T4 / Env.DTE / XSLT are used to automate your codesnippets I would <a href="http://www.codeproject.com/KB/codegen/CodeSnippetAutomation.aspx">encourage you to read my codeproject article</a>.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2011/04/viewmodel-inotifypropertychanged-code-generation/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<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>
		<item>
		<title>Declarative Dependency Property Definition with T4 + DTE</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/08/declarative-dependency-property-definition-with-t4-dte/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/08/declarative-dependency-property-definition-with-t4-dte/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 10:41:22 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[dependency properties]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=491</guid>
		<description><![CDATA[This blog post describes a technique for specifying WPF / Silverlight Dependency Properties declaritively via attributes as illustrated by the following example: &#91;DependencyPropertyDecl&#40;&#34;Maximum&#34;, typeof&#40;double&#41;, 0.0&#41;&#93; &#91;DependencyPropertyDecl&#40;&#34;Minimum&#34;, typeof&#40;double&#41;, 0.0&#41;&#93; public partial class RangeControl : UserControl &#123; ... &#125; At design-time the declarations are read via a T4 template and the required code is generated. For more [...]]]></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%252F2009%252F08%252Fdeclarative-dependency-property-definition-with-t4-dte%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Declarative%20Dependency%20Property%20Definition%20with%20T4%20%2B%20DTE%20%23%22%20%7D);"></div>
<p>This blog post describes a technique for specifying WPF / Silverlight Dependency Properties declaritively via attributes as illustrated by the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>DependencyPropertyDecl<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Maximum&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">0.0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>DependencyPropertyDecl<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Minimum&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">0.0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> RangeControl <span style="color: #008000;">:</span> UserControl
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>At design-time the declarations are read via a T4 template and the required code is generated. For more information, read on &#8230;</p>
<p>A few months ago I wrote an article on codeproject about a technique for <a href="http://www.codeproject.com/KB/WPF/DependencyPropertyCodeGen.aspx">generating dependency properties via T4 templates</a>. In brief; with this technique, you provide an XML description of your classes and their dependency properties, run the T4 template, and partial classes are generated which contain these properties &#8211; no more writing DP boiler plate code! For those of you who are unfamiliar with T4, it is a code generation engine which is built into Visual Studio, for a primer, I refer you to my <a href="http://www.codeproject.com/KB/WPF/DependencyPropertyCodeGen.aspx">codeproject article</a>.</p>
<p>A few days back Daniel Vaughan published a blog post about using T4 templates to <a href="http://danielvaughan.orpius.com/post/MetaGen-A-project-metadata-generator-for-Visual-Studio-using-T4.aspx#comment">generate project meta-data</a>. He demonstrated how this could be used to solve the age-old problem of hard-coded property name strings when implementing INotifyPropertyChanged. His solution uses both T4 and DTE &#8211; an automation library which allows you to programmatically access the items within your projects and solutions. Daniel&#8217;s blog post inspired me to revisit my DP code generation solution in order to simplify it and remove the need for the XML file. </p>
<p>My first step was to define a custom attribute which can be used to indicate that a class requires the template to generate a DP:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>AttributeUsage<span style="color: #008000;">&#40;</span>AttributeTargets<span style="color: #008000;">.</span><span style="color: #6666cc; font-weight: bold;">Class</span> , AllowMultiple <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> DependencyPropertyDecl <span style="color: #008000;">:</span> Attribute
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> DependencyPropertyDecl<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> name, Type type, <span style="color: #6666cc; font-weight: bold;">object</span> defaultValue<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">name</span> <span style="color: #008000;">=</span> name<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">type</span> <span style="color: #008000;">=</span> type<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">defaultValue</span> <span style="color: #008000;">=</span> defaultValue<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> name<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Type type<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> defaultValue<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>With DTE it should be possible to inspect all the classes in the project, identifying those for which this attribute exists  and generate the required DPs. However, looking at the DTE APIs this is not such an easy task, whilst the API defines a &#8216;base&#8217; interface CodeElement from which CodeClass, CodeNamespace etc&#8230; derive, there is no unified concept of &#8216;Children&#8217;, also the Project and Solution are not CodeElements. In other words, in order to find all the classes in a solution you must recurse over a heterogeneous collection of classes and properties.</p>
<p>In order to ease the task of locating the classes within the project that have the DependencyPropertyDecl attribute associated, I created a simple Linq-to-DTE implementation:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>CodeElement<span style="color: #008000;">&gt;</span> CodeElementsInProjectItems<span style="color: #008000;">&#40;</span>ProjectItems projectItems<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>ProjectItem projectItem <span style="color: #0600FF; font-weight: bold;">in</span> projectItems<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>CodeElement el <span style="color: #0600FF; font-weight: bold;">in</span> CodeElementsInProjectItem<span style="color: #008000;">&#40;</span>projectItem<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> el<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>CodeElement<span style="color: #008000;">&gt;</span> CodeElementsInProjectItem<span style="color: #008000;">&#40;</span>ProjectItem projectItem<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    FileCodeModel fileCodeModel <span style="color: #008000;">=</span> projectItem<span style="color: #008000;">.</span><span style="color: #0000FF;">FileCodeModel</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>fileCodeModel <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>CodeElement codeElement <span style="color: #0600FF; font-weight: bold;">in</span> fileCodeModel<span style="color: #008000;">.</span><span style="color: #0000FF;">CodeElements</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//WalkElements(codeElement, null);</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>CodeElement el <span style="color: #0600FF; font-weight: bold;">in</span> CodeElementDescendantsAndSelf<span style="color: #008000;">&#40;</span>codeElement<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> el<span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>projectItem<span style="color: #008000;">.</span><span style="color: #0000FF;">ProjectItems</span> <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>ProjectItem childItem <span style="color: #0600FF; font-weight: bold;">in</span> projectItem<span style="color: #008000;">.</span><span style="color: #0000FF;">ProjectItems</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>CodeElement el <span style="color: #0600FF; font-weight: bold;">in</span> CodeElementsInProjectItem<span style="color: #008000;">&#40;</span>childItem<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> el<span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>        
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>CodeElement<span style="color: #008000;">&gt;</span> CodeElementsDescendants<span style="color: #008000;">&#40;</span>CodeElements codeElements<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>CodeElement element <span style="color: #0600FF; font-weight: bold;">in</span> codeElements<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>CodeElement descendant <span style="color: #0600FF; font-weight: bold;">in</span> CodeElementDescendantsAndSelf<span style="color: #008000;">&#40;</span>element<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> descendant<span style="color: #008000;">;</span>                
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>CodeElement<span style="color: #008000;">&gt;</span> CodeElementDescendantsAndSelf<span style="color: #008000;">&#40;</span>CodeElement codeElement<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> codeElement<span style="color: #008000;">;</span>
&nbsp;
    CodeElements codeElements<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">switch</span><span style="color: #008000;">&#40;</span>codeElement<span style="color: #008000;">.</span><span style="color: #0000FF;">Kind</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>        
&nbsp;
        <span style="color: #008080; font-style: italic;">/* namespaces */</span>
        <span style="color: #0600FF; font-weight: bold;">case</span> vsCMElement<span style="color: #008000;">.</span><span style="color: #0000FF;">vsCMElementNamespace</span><span style="color: #008000;">:</span>
        <span style="color: #008000;">&#123;</span>
            CodeNamespace <span style="color: #008080;">codeNamespace </span><span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>CodeNamespace<span style="color: #008000;">&#41;</span>codeElement<span style="color: #008000;">;</span>                                        
            codeElements <span style="color: #008000;">=</span> codeNamespace<span style="color: #008000;">.</span><span style="color: #0000FF;">Members</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>CodeElement descendant <span style="color: #0600FF; font-weight: bold;">in</span> CodeElementsDescendants<span style="color: #008000;">&#40;</span>codeElements<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> descendant<span style="color: #008000;">;</span>                
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/* Process classes */</span>
        <span style="color: #0600FF; font-weight: bold;">case</span> vsCMElement<span style="color: #008000;">.</span><span style="color: #0000FF;">vsCMElementClass</span><span style="color: #008000;">:</span>
        <span style="color: #008000;">&#123;</span>            
            CodeClass codeClass <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>CodeClass<span style="color: #008000;">&#41;</span>codeElement<span style="color: #008000;">;</span>            
            codeElements <span style="color: #008000;">=</span> codeClass<span style="color: #008000;">.</span><span style="color: #0000FF;">Members</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>CodeElement descendant <span style="color: #0600FF; font-weight: bold;">in</span> CodeElementsDescendants<span style="color: #008000;">&#40;</span>codeElements<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>                
                <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> descendant<span style="color: #008000;">;</span>                
            <span style="color: #008000;">&#125;</span>            
            <span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>    
        <span style="color: #008000;">&#125;</span>        
    <span style="color: #008000;">&#125;</span>    
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>There might be simpler way of achieving this, it is the first time I have created a recursive IEnumerable implementation, so please let me know if I have done something stupid! For a much more elegant solution to the problem of creating an IEnumerable implementation on a tree like structure via recursion have a look at <a href="http://mutable.net/blog/archive/2008/05/23/using-linq-to-objects-for-recursion.aspx">this blog post by David Jade</a>. However, as I mentioned earlier, the heterogeneous nature of the DTE API onto the project structure prohibits this method. </p>
<p>Anyhow, with this nasty IEnumerable implementation out of the way, we can use the power of Linq to provide a concise implementation of &#8216;Find all the classes in the solution which have one or more DependencyPropertyDecl attributes&#8217;, and perform the required code-gen as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// for details of how the DTE 'project' is located see Daniel's blog post or the attached source of this blog.</span>
var elements <span style="color: #008000;">=</span> CodeElementsInProjectItems<span style="color: #008000;">&#40;</span>project<span style="color: #008000;">.</span><span style="color: #0000FF;">ProjectItems</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var classes <span style="color: #008000;">=</span> elements<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>el <span style="color: #008000;">=&gt;</span> el<span style="color: #008000;">.</span><span style="color: #0000FF;">Kind</span> <span style="color: #008000;">==</span> vsCMElement<span style="color: #008000;">.</span><span style="color: #0000FF;">vsCMElementClass</span><span style="color: #008000;">&#41;</span>
                               <span style="color: #008000;">.</span><span style="color: #0000FF;">Cast</span><span style="color: #008000;">&lt;</span>CodeClass<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>cl <span style="color: #008000;">=&gt;</span> Attributes<span style="color: #008000;">&#40;</span>cl<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Any</span><span style="color: #008000;">&#40;</span>at <span style="color: #008000;">=&gt;</span> at<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">==</span><span style="color: #666666;">&quot;DependencyPropertyDecl&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>var clazz <span style="color: #0600FF; font-weight: bold;">in</span> classes<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    GenerateClass<span style="color: #008000;">&#40;</span>clazz<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The GenerateClass function is a simple modification of the one I wrote for generating classes based on XML descriptions. In this implementation we acquire the CodeAttribute.Value property for each of our custom attribute instances and from there obtain the DP name, type and default value:</p>
<pre>
<#+
///
<summary>
/// Generates a class along with its associated DPs
/// </summary>

private void GenerateClass(CodeClass clazz)
{
    string classNamespace = clazz.Namespace.Name;
    string className =  clazz.Name;

    bool classRaisesPropertyChanged = false;

#>

namespace <#= classNamespace #>
{
    public partial class <#= className #> <#+ if(classRaisesPropertyChanged){ #>: INotifyPropertyChanged<#+ } #>
    {
<#+
    var attributes = Attributes(clazz).Where(att => att.Name=="DependencyPropertyDecl");
    foreach(CodeAttribute attribute in attributes)
    {
        string[] attributeValues = attribute.Value.Split(',');

        string propertyName = attributeValues[0].Trim().Replace("\"","");
        string propertyType = attributeValues[1].Trim().Substring(7, attributeValues[1].Length - 9);
        string summary = null;
        string metadata = null;
        string defaultValue = attributeValues[2].Trim();
        string typeConverter = null;
        bool propertyChangedCallback = true;
        bool isAttached = false;
        #>

        #region <#= propertyName #>
        <#+        

        GenerateCLRAccessor(typeConverter, propertyType, propertyName, summary);

        bool handleDPPropertyChanged = propertyChangedCallback || classRaisesPropertyChanged;

        GenerateDependencyProperty(className, propertyType, defaultValue, propertyName,
                                   handleDPPropertyChanged, isAttached, metadata, summary);        

        if (handleDPPropertyChanged)
        {
            GenerateChangeEventHandler(className, propertyName, propertyChangedCallback, classRaisesPropertyChanged);
        } 

        if (isAttached)
        {
            GenerateAttachedPropertyAccessor(propertyName, propertyType);
        }
        #>
        #endregion
    <#+
    } // end foreach dps

    if (classRaisesPropertyChanged)
    {
        GenerateINotifyPropertChangedImpl();
    }
    #>
    }
}

<#+
}
#>
</pre>
<p>(please forgive the lack of syntax highlighting wordpress/codeproject do not support T4 templates!)</p>
<p>The GenerateCLRAccessor, GenerateDependencyProperty, &#8230; functions are re-used from my previous XML-based approach to DP generation.</p>
<p>For a simple demonstration of this approach, here is the complete implementation for a simple range control which has a Maximum and Minimum property, where if the user enters a Minimum which is greater that the Maximum, the values are swapped:</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;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;WpfDeclarativeDPCodeGen.RangeControl&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:x</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">DataContext</span>=<span style="color: #ff0000;">&quot;{Binding RelativeSource={RelativeSource Self}}&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> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Horizontal&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;">Width</span>=<span style="color: #ff0000;">&quot;50&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Minimum}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBlock</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot; : &quot;</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&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;">Width</span>=<span style="color: #ff0000;">&quot;50&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;{Binding Maximum}&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;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>DependencyPropertyDecl<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Maximum&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">0.0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>DependencyPropertyDecl<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Minimum&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">0.0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>TypeConverter<span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> RangeControl <span style="color: #008000;">:</span> UserControl
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> RangeControl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        InitializeComponent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// If max is less than min, swap their values</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Swap<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>Maximum <span style="color: #008000;">&lt;</span> Minimum<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #6666cc; font-weight: bold;">double</span> swap <span style="color: #008000;">=</span> Minimum<span style="color: #008000;">;</span>
            Minimum <span style="color: #008000;">=</span> Maximum<span style="color: #008000;">;</span>
            Maximum <span style="color: #008000;">=</span> swap<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnMaximumPropertyChanged<span style="color: #008000;">&#40;</span>DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Swap<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnMinimumPropertyChanged<span style="color: #008000;">&#40;</span>DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Swap<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>When using this approach the workflow is quite simple, create your class, add the DependencyPropertyDecl attributes, then execute the code generation template. The output is an accompanying partial class which contains the DP code itself, plus partial methods which can be implemented in order to perform logic when the property changes.</p>
<p>I have not-yet completely ported my XML-based DP generation templates to this new declarative approach, for example the DependencyPropertyDecl attribute needs to also indicate property meta-data, whether a property is attached etc &#8230; However, I thought I would share my ideas in case I didn&#8217;t get the time (or urge) to make a complete  implementation. </p>
<p>I feel that this approach has great potential far beyond DP code generation, simple examples could include attributes that indicate that a T4 template should generate a &#8216;generic&#8217; INotifyPropertyChanged or IEditableObject implementation, and of course, the more complex application-specific possibilities are endless. </p>
<p>You can download an example project containing the RangeControl above: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/08/WpfDeclarativeDpCodeGen1.zip'>WpfDeclarativeDpCodeGen.zip</a></p>
<p>Try adding new DependencyPropertyDecl attributes, and re-run the code generation template (right click CodeGen/GeneratedObjects.tt -> Run Custom Tool), and inspect the generated output &#8211; CodeGen/GeneratedObjects.cs.</p>
<p>Finally, thanks to Daniel Vaughan for the inspiration.</p>
<p>Regards,<br />
Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/08/declarative-dependency-property-definition-with-t4-dte/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

