Redirecting between views in MVVM

I am using MVVM patern to develop my WPF application. It works great for unrelated pages, means how to navigate to another view from one view.

For example: I have one list page where some entries come from one ViewModel and another from another ViewModel, means I have two ViewModels for my only view. And now I want to display another view on some event.

I am using the IsSelected property for change notification. This mechanism only works as long as any action performed on the same ViewModel that I have to do for such a senario.

+2


source to share


2 answers


MVVM as a pattern is about separating concerns, increasing the test likelihood of your code, etc., so your ViewModel should only be concerned with enforcing business rules and providing data for your view.

You will need to use this in conjunction with some kind of MVC pattern where the Controller problem handles the navigation / state of the application, etc.

(edit) For example, imagine your application has a login screen, so you create a LoginView that contains a username and password; probably an OK button and a Cancel button.

You create a LoginViewModel class to bind this view and handle the login logic in this class.

But once the application is logged in, you don't have to know what it takes to log in to the ViewModel. or what kind to display next .. maybe you want to go to this user's last screen the previous time they logged in? Maybe it goes to the default screen according to the user profile? This solution has nothing to do with the login function ...



So, if you create a Controller class, you can: create an instance of the LoginViewModel class, and then depending on the result of the login, apply the business rules required to remove the LoginViewModel from scope and create a new ViewModel (like HomePageViewModel), etc. etc.

Finally, you will need to tell the application which views to use for each virtual machine using DataTemplates

There are tons of other ways to dump this special cat, of course ... that's just one idea ...

While the core concept remains: use MVVM to bridge the gap between View and Model in a clean, testable way ... don't try to make it "one pattern fits all" :)

HTH :)

+2


source


I agree with IanR to use a controller for workflow / navigation.



The WPF Application Framework (WAF) Sample ViewModel shows how you can do this.

0


source







All Articles