Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

MVVM Friendly DataTemplate switching

4.94/5 (16 votes)
29 Jul 2013CPOL 50K  
Switching data templates entirely in XAML.
I frequently have a need to switch templates inside listviews. Now, while you could create your own ItemTemplateSelector to choose templates, this just smacks to me of having to add more code to your application than really should be necessary. It would be great if you could do this entirely in XAML.
 
Well, thanks to the great Dr WPF for suggesting it, there is and it's a really simple trick. What you need to do is have your DataTemplate just wrap a Control, and swap in ControlTemplates as necessary.
XML
<DataTemplate x:Key="MyItemTemplate">
  <Control x:Name="myControl" Template="{StaticResource MyMainTemplate}" />
  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding IsActive}" Value="True">
      <Setter TargetName="myControl" Property="Template" Value="{StaticResource MyOtherTemplate}" />
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>
Now all you need do is add the templates as ControlTemplates instead of DataTemplates and point your listview at this DataTemplate.
 
As you can see, the coding is all done in your XAML and, through the judicious use of data triggers, you can have swappable templates. You've gotta love it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)