I have a WPF application with multiple views. I want to switch from view 1 to view 2 and from there I can switch to multiple views. So I want a button on view 1 that loads view2 in the same window.
I tried those things, but can't get it to work.
- How to navigate through windows with MVVM Light for WPF?
- https://galasoft.ch/posts/2011/01/navigation-in-a-wp7-application-with-mvvm-light
From the first link, the problem is that I don't understand the ViewModelLocator code. They call the CreateMain();
function but where is this defined, and how can I switch to another view from inside a view.
Best Answer
Firstly, you don't need any of those toolkits/frameworks to implement MVVM. It can be as simple as this... let's assume that we have a
MainViewModel
, andPersonViewModel
and aCompanyViewModel
, each with their own related view and each extending anabstract
base classBaseViewModel
.In
BaseViewModel
, we can add common properties and/orICommand
instances and implement theINotifyPropertyChanged
interface. As they all extend theBaseViewModel
class, we can have this property in theMainViewModel
class that can be set to any of our view models:Of course, you'd be implementing the
INotifyPropertyChanged
interface correctly on your properties unlike this quick example. Now inApp.xaml
, we declare some simpleDataTemplate
s to connect the views with the view models:Now, wherever we use one of our
BaseViewModel
instances in our application, theseDataTemplate
s will tell the framework to display the related view instead. We can display them like this:So all we need to do now to switch to a new view is to set the
ViewModel
property from theMainViewModel
class:Finally, how do we change the views from other views? Well there are several possible ways to do this, but the easiest way is to add a
Binding
from the child view directly to anICommand
in theMainViewModel
. I use a custom version of theRelayComand
, but you can use any type you like and I'm guessing that you'll get the picture:In the child view XAML:
That's it! Enjoy.