Dynamically change DataTemplate for a ListView at Runtime


Staff member
I have 2 DataTemplates for displaying the contents of ClassA or ClassB inside a single ListView; which template to select will be based on a RadioButton selection by the user.

Is it possible to change the ItemTemplate of a ListView (in XAML) based on user input dynamically at runtime?

An example snippet of code:

XAML Page:<br/>

        &lt;DataTemplate x:Key="ClassAListViewItemTemplate" x:DataType="vm:ClassA" ... /&gt;
        &lt;DataTemplate x:Key="ClassBListViewItemTemplate" x:DataType="vm:ClassB" ... /&gt;    
        &lt;RadioButton Content="ClassA" ... /&gt;
        &lt;RadioButton Content="ClassB" ... /&gt;
        &lt;ListView DataContext="{Binding Path=MainViewModel}"
                  ItemsSource="{Binding ListOfClassAOrB, Mode=TwoWay}"
                  ItemTemplate="{StaticResource ClassAListViewItemTemplate}"/&gt;

I have stripped the code down somewhat to the essentials, but I would like to be able to change the following at runtime:

ItemTemplate="{StaticResource ClassAListViewItemTemplate}"

I have seen solutions for Classic WPF applications that use Style.Triggers, but these aren't applicable for UWP

Marco Minerva's blog on <a href="https://marcominerva.wordpress.com/...d-datatemplate-in-universal-windows-platform/" rel="nofollow">Adaptive Triggers, RelativePanel and DataTemplate in the Universal Windows Platform</a> talks of using UserControls within DataTemplates to modify the visual state using Adaptive Triggers, but this doesn't take into account switching out of templates based on user input

The closest answer I have found to my problem is another blog he wrote "<a href="https://marcominerva.wordpress.com/2013/02/18/dynamically-choose-datatemplate-in-winrt/" rel="nofollow">Dynamically choose DataTemplate in WinRT</a>" where there is an element of code-behind involved - but it only appears to be an if statement - but its the cleanest solution I have come across thus far, and what I'd like to replicate in XAML