Adam Rackis
Adam Rackis

Reputation: 83358

Changing DataTemplates at Runtime

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?

Upvotes: 2

Views: 3605

Answers (1)

Stephan
Stephan

Reputation: 5488

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.

Upvotes: 2

Related Questions