DTE and T4 - Better Together

A couple of folks out there have put together some really neat T4 templates that use the host-specific flag and then access Visual Studio's DTE object model to read state from other code in the project and use that as metadata for code generation.

Daniel Vaughan started out with a  nice post on using DTE to explore the source constructs within your project using the CodeModel and thence using that data to  introduce compile time strong-typing to WPF binding expressions.

To borrow Daniel's example, to switch from this weakly typed case

 <StackPanel DataContext="{Binding Source={StaticResource Person}}">
    <TextBlock >Name:</TextBlock>
    <TextBox Text="{Binding Name}" />

to this strongly typed one which gives compile-time errors if you get the name wrong

 <StackPanel DataContext="{Binding Source={StaticResource Person}}">
 <TextBlock >Name:</TextBlock>
   <TextBox Text="{Binding Path={x:Static Metadata:PersonMetadata.NamePath}}"/>

He then also talks about using the same technique to generate implementations of INotifyPropertyChange that are robust to refactoring without the problems of embedded strings or the performance hit of reflection.  Code generation and declarative programming are often criticized for not having good support for refactoring, so it's nice to see a use case that actually helps support refactoring.

Daniel has now expanded this into a full article on The Code Project.


Last time, I talked about Colin Eberhardt's article for generating Dependency Properties from an xml file.  Daniel's approach inspired Colin to go back and rework his example to use DTE replacing his external XML file with custom attributes on classes to simply add dependency properties like so:

 [DependencyPropertyDecl("Maximum", typeof(double), 0.0)]
[DependencyPropertyDecl("Minimum", typeof(double), 0.0)]
public partial class RangeControl : UserControl

Very cool stuff.

Technorati Tags: T4,DTE,Visual Studio 2008,Code Generation,Dependecy Property,Databinding,Strongly-typed