views:

21

answers:

2

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?

+1  A: 

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.

Stephan
A: 

This seems to be the "best" bet:

http://www.e-pedro.com/2009/06/using-data-binding-with-static-resources-in-wpf/

Or of course you could manually pass the actual template as the parameter to a different command:

<Button Width="50" Command="{Binding ChangeTemplateCommand}" CommandParameter="{StaticResource vmDataTemplate}">White</Button>
<Button Width="50" Command="{Binding ChangeTemplateCommand}" CommandParameter="{StaticResource vmDataTemplate2}">Lavender</Button>

<ListBox x:Name="bookListBox" Grid.Row="0" ItemsSource="{Binding Path=BookSource}" ItemTemplate="{Binding Path=ItemSourceTemplate}">

And then in ViewModel:

ChangeTemplateCommand = new RelayCommand(template => {
    this.ItemSourceTemplate = (DataTemplate)template;
    PropertyChanged(this, new PropertyChangedEventArgs("ItemSourceTemplate"));
});
Adam