What is the best way to handle navigation in a WPF application after an MVVM pattern?

I saw that this was done inside the event handler directly after the .xaml file, however it does not seem to follow the MVVM pattern: MainApplication.mainFrame.Navigate(new HomePage()); . Is there a better way to handle navigation using the MVVM pattern, possibly in the ViewModel? or in xaml?

+4
source share
2 answers

If you are looking for different UserControls based on the context of your data, just check out the next simple DataBinding and DataTemplate concept and extend it. Imagine you have a property called CurrentViewModel that binds to the contents of the ContentControl inside your window.

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

Now imagine that you have ViewModel classes ClassA and ClassB, so set the instances in CurrentViewModel accordingly 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, View is automatically controlled from the ViewModel logic, and WPF will take care of displaying the UserControl on the Datatemplate.

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

+8
source

I think that what you are trying to do would be easier to do if you had navigation in a different class. See below

 public class FirstViewModel { } public class SecondViewModel { } public class NavigateViewModel { public ViewModelBase CurrentVieModel {get;set;} public bool CanNavigate { get { return true;//Or Add some custom logic here determine if you can navigate} } public void Navigate() { //Just some arbitrary code if(CurrentViewModel is FirstViewModel) CurrentViewModel = new SecondViewModel(); } } 

Now just 1) bind the contents of the page to CurrentViewModel 2) Wrap the navigation method in ICommand and you will set

May not suit your needs, hope this helps

+2
source

Source: https://habr.com/ru/post/1302651/


All Articles