I am trying to implement the MVVM design patern for mt WPF application. In order to connect the view to the viewmodels, I use a ResourceDictionary
(used in Application.Resources
), that looks like
<DataTemplate DataType={x:Type viewmodel:SampleViewModel}>
<view:SampleView1 />
</DataTemplate>
The view models are then simply put into content presenters to display them.
Now, when the user presses a button, I'd like to display SampleViewModel
using a different view. How do I change the data template used for SampleViewModel
?
Less words more code. As far as you said, you have the class
SampleViewModel
. I added the propertyTitle
for demonstration andViewType
for identifying the correct view:The
DataTemplateSelector
for two views depending on theViewType
property:Xaml code:
The main part is in the class
MainViewModel
where I've put the logic for switching views:The
SwitchViewCommand
can be any type of command, I use the command from the mvvmlight library.Inside the handler of the command I change the type of viewmodel and update the property
ItemViewModel
in a tricky way because aContentControl
refreshes a view only if to change the Content property, and this property will not be changed unless you set a reference to different object.I mean, even the code
this.ItemViewModel = this.itemViewModel
will not change the view. It's strange, but the workaround doesn't require much work.You can override the mapping by placing a similar resource lower down in the tree. Since WPF will resolve the resource by searching upwards, such an override will replace your existing mapping.
You can achieve this in many different ways depends upon the architecture you want.