Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to handle navigation in a WPF application following the MVVM pattern?

I've seen this done inside of an event handler directly behind the .xaml file however it doesn't seem like this would follow the MVVM pattern: MainApplication.mainFrame.Navigate(new HomePage());. Is there a better way for handling navigation with the MVVM pattern perhaps in the ViewModel? or in the XAML?

like image 404
Mike Avatar asked Dec 30 '22 00:12

Mike


1 Answers

If you are looking for showing different UserControls based on the context of your data, then just understand the following simple DataBinding and DataTemplate concept and expand on it. Imagine you got a Property called CurrentViewModel which binds to the Content of a ContentControl inside your Window

 <Window ... 
    <ContentControl Content="{Binding CurrentViewModel}" />
 </Window>

Now imagine that you got ViewModel classes ClassA and ClassB, so appropriately set the instances to CurrentViewModel and define global DataTemplates (Views) for your classes

<DataTemplate DataType="{x:Type vm:ClassA}">
    <local:UserControlForA../>
</DataTemplate>


<DataTemplate DataType="{x:Type vm:ClassB}">
    <local:UserControlForB../>
</DataTemplate>

Now the View is automatically controlled from ViewModel logic and WPF will take care of showing the UserControl by Datatemplate.

If you are not familiar with MVVM better use this article. http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

like image 66
Jobi Joy Avatar answered Jan 14 '23 13:01

Jobi Joy