wpf – Changing DataTemplates at Runtime – Education Career Blog

I’d like to be able to swap out data templates at runtime, but without the

FindResource("fdds") as DataTemplate

Type of code I’ve seen a lot. I’d like to be able to just bind the template to look for the resource according to a property in my ViewModel. Conceptually I’d like to be able to do this, but the compiler obviously doesn’t like it:

 ... ItemTemplate="{StaticResource {Binding Path=VMTemplate}}">

And then other commands would change the value of VMTemplate in the ViewModel. Is there a way to do something like this?

,

StaticResource extension is an immediate lookup when the XAML is parsed which means the Resource must be present at the start of the app. In order to set a template dynamically you will have to do something similar to the way your first line looks.

A possibility I have seen would be to make the DataTemplate have a custom control that extends ContentControl that has multiple DataTemplate properties that would then be able to select different templates based on a bound value from your View Model.

Leave a Comment