switch UserControl

Jul 12, 2013 at 2:57 PM
Hi all,

I'm new to MVVM. Currently i have do some tests with the example Code.
Now i write my own little WPF example with two ViewModels, two Views(UserControls) and two Models .

My question is how i can switch between UserControls?
Have anyone a little example for me?

Jul 12, 2013 at 3:35 PM
There is a navigation sample project included with the toolkit. It is Silverlight, but it may help you.
Sep 7, 2013 at 6:57 PM
Edited Sep 7, 2013 at 6:58 PM
You may want to look at Rachel Lim's blog about Navigation with MVVM. I just found it myself and it is geared toward WPF, not Silverlight.
Oct 26, 2013 at 9:41 PM
Hi tooom,
I've been experimenting with the technique I referenced above. This is a pattern that uses a UserControl as a DataTemplate for a ViewModel. I've seen it referred to a the ViewModel First Pattern.

In your XAML, in the place where you want the UserControl to appear you can put in a ContentControl and set it's Binding to the selected ViewModel you want to display (as a UserControl). You make the association between ViewModels and the UserControls by declaring DataTemplates in XAML Resources. For instance you could place a ContentControl within a Border and use Border.Resources to Declare the DataTemplates.

In the ViewModel supporting the larger container view, you could have an Observable Collection of ViewModels (as Objects), and a SelectedViewModel (as Object). Then when the SelectedViewModel changes, the UserControl associated with it appears in the ContentControl.
``` <Border Grid.Column="1" Grid.Row="1">
            <DataTemplate DataType="{x:Type vm:MyViewModel1}" >
            <DataTemplate DataType="{x:Type vm:MyViewModel2}" >
            <ContentControl  Content="{Binding SelectedViewModel}" ></ContentControl>
But when using SimpleMVVM we typically instantiate the ViewModel for a UserControl in the UserControl's XAML and use the DataBinding to help with intellisense in development. You have to take that out before you run the project, otherwise, you will get a newly intantiated ViewModel for the user control when it appears, which may not be what you want.

I hope this helps.