Jerry Nixon @Work: Implementing the WPF DataTemplateSelector

Jerry Nixon on Windows

Thursday, August 4, 2011

Implementing the WPF DataTemplateSelector

The DataTemplateSelector allows you to swap between DataTemplates based on logic in your code behind. By default, WPF will swap between DataTemplates of different types, but sometimes the Type does not change, only the Templates, based on some Property value (for example).

The Code Behind:

It's worth pointing out that the Selector only executes when the Content of the ContentControl changes. This means the data influencing the Data Template could change without effecting the selected Data Template. If you want this to be more dyanmic, you will need to use a DataTrigger - but the logic for a DataTrigger is more limited, or requires a ValueConverter which just complicates the whole matter.