A Dynamic DataTemplate Generator for WPF

This morning I was experimenting with the idea of dynamically generating a DataTemplate for any object in WPF.

What I ended up with was a DataTemplateSelector which, given an object, will return a new DataTemplate that displays all the information it can glean from that object.

Here's my proof of concept. First I defined a class that uses some data annotations:

public class Child
{
    [Display(Name = "Details", Order = 2)]
    public string Description { get; set; }

    [Display(Description = "The time at which this object was initialized")]
    [DisplayName("Timestamp")]
    public DateTime Date { get; set; }
}

Then I used that class, inside an instance of an anonymous type, as the DataContext of my Window:

public MainWindow()
{
    InitializeComponent();

    this.DataContext = new
    {
        Name = "Awesome",
        Level = 100,
        Child = new Child
        {
            Description = "Foo",
            Date = DateTime.Now,
        },
        Children = Enumerable.Range(1, 5)
            .Select(n => new Child { Description = "Child " + n })
            .ToList(),
    };
}

As you can see, I've got raw properties, a nest class and a collection of objects there.

My XAML, then, simply displays the DataContext using my DataTemplateSelector:

<Window.Resources>
    <my:AutoTemplateSelector x:Key="fred" />
</Window.Resources>

<ContentControl Content="{Binding}" ContentTemplateSelector="{StaticResource fred}" />

Here's the result:

A dynamically generated DataTemplate

As you can see, it displays raw properties as TextBlocks, object properties as a nested grid, and collection properties as an ItemsControl. It also honours any display name and order you give your properties using data annotations.

I've posted the code for the AutoTemplateSelector class as a Gist over here. Keen to hear your thoughts!

wpf xaml
Posted by: Matt Hamilton
Last revised: 01 Aug, 2013 10:44 PM History

Trackbacks