WPF: switching UserControls depending on corresponding ViewModels (MVVM)
Is it possible to deduce the necessary user control based on a ViewModel type?
You mean, like this?
<Window.Resources>
<DataTemplate DataType="{x:Type vm:LionViewModel}">
<v:LionView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SnakeViewModel}">
<v:SnakeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:BirdViewModel}">
<v:BirdView/>
</DataTemplate>
</Window.Resources>
See "Applying a View to a View Model" in Josh Smith's article on MVVM.
Edit:
Here's a trivial example of type-based template selection that you can paste into Kaxaml to prove to yourself that it really works:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Page.Resources>
<sys:String x:Key="string">this is a string</sys:String>
<sys:Int32 x:Key="int32">1234</sys:Int32>
<DataTemplate DataType="{x:Type sys:String}">
<TextBlock Foreground="Red" Text="{Binding}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type sys:Int32}">
<TextBlock Foreground="Blue" Text="{Binding}"/>
</DataTemplate>
</Page.Resources>
<StackPanel>
<ContentControl Content="{Binding Source={StaticResource string}}"/>
<ContentControl Content="{Binding Source={StaticResource int32}}"/>
</StackPanel>
</Page>
You can use DataTemplateSelector for that. The method of choosing the right template is up to you. You can use enums or test for class type if you wish.