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")]
    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()

    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 })

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:

    <my:AutoTemplateSelector x:Key="fred" />

<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: 20 Feb, 2017 08:20 PM History