Reputation: 11
I have a mainwindow with viewmodel and 2 usercontrols with their own viewmodels. When the app launches usercontrol1 is added to displayviewmodel of mainwindow. In usercontrol1 there is a button to launch usercontrol2 and within usercontrol2 is a button to bring you back to usercontrol1.
I want usercontrol2 to overlay usercontrol1 and when I'm done with usercontrol2 I want it disposed. The displayViewModel is in mainwindow viewmodel and I cant figure out for the life of me how to change displayviewmodel without creating new instances of mainwindow. My initial thought was to route the button commands to maindowviewmodel, but I stumbled on how to do that.. any suggestions?
Upvotes: 1
Views: 90
Reputation: 42344
The problem you have here can be solved by allowing MainWindowViewModel
to orchestrate the switching of the DisplayViewModel
. MainWindowViewModel
should hold a reference to UserControl1ViewModel
and UserControl2ViewModel
. When a request is made to switch to the other UserControl, the view model for the current UserControl should communicate the switch request by publishing an event or message, which MainWindowViewModel subscribes to.
If you use this technique, you can manage the switching of the UserControls within your MainWindow by using a combination of DataTemplates and ContentControl.
To do this, first add these resources:
<Window.Resources>
<DataTemplate DataType="{x:Type vm:UserControl1ViewModel}">
<v:UserControl1/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UserControl2ViewModel}">
<v:UserControl2/>
</DataTemplate>
</Window.Resources>
Then place a ContentControl where you'd like the UserControl to appear.
<ContentControl Content="{Binding DisplayViewModel}" />
As long as your view model implements INotifyPropertyChanged
, when you set DisplayViewModel
to a new view model, the UserControls will automatically be switched out.
Upvotes: 0
Reputation: 31576
The displayViewModel is in mainwindow viewmodel and I cant figure out for the life of me how to change displayviewmodel without creating new instances of mainwindow.
I am of the belief that usercontrols do not need a VM, only pages. Usercontrols should be self-contained stateless entities with dependency properties which are data passed into the control to do its job.
If one has a main or centralized ViewModel, it should be handling all the data needs and page viewing operations and keep track of the current state of the application. One should subscribe from the VM to the control of User2 and when it signals a change, it is the MainVM to do the actual change.
MVVM is just a fancy way of doing three tiered data systems whose job it is to separate database, from view, from operations. It is not a religion but a general guideline. IMHO
Redo the business and display logic processing by centralizing it into one VM. By avoiding a loose confederation of viewmodels and centralizing the operations into one main VM will achieve the goal set forth.
Upvotes: 1