MVVM. Should the View affect the MainWindow ViewModel?

I hope this is a simple, albeit contrived question about MVVM.

My MainWindow has 1 control, ContentControl, which displays one of two views. I want to be able to switch between the two views using a button. The problem is that buttons will control each view. EG View1 has a button and View2 has a button. Only 1 view is shown in the UI, and when the button is clicked, another view is shown. However, to do this, it would mean that the ViewModel View needs to know about the MainWindow ViewModel in order to change the view. It doesn't seem right.

The problem could be my MainWindow ViewModel. One of the projects is public object View {get; set} and this is what binds to the MainWindows ContentControl. So this is the property that needs to be updated from the View model.

Does the MVVM pattern oppose if the View updates the MainWindow of the ViewModel?

+3


source to share


2 answers


I'm not sure if I fully understand your question, but a good technique for communicating between views is either via EventAggregator or Messenger template. These two implement pub / sub in connected mode.

This is an example MVVMLight Toolkit Messenger http://dotnet.dzone.com/articles/mvvm-light-whats-messenger

This is a Prism EventAggregator example for sharing information between viemodels http://rachel53461.wordpress.com/2011/06/05/communication-between-viewmodels-with-mvvm/



hope this helps.

Edit: Ok, my answer is still valid. If you are using pub / sub like above, you would say view1

and view2

send a view change message, for example, and define a target (for example target maybe view2

). You will then subscribe to yours MainViewModel

for each change submission message. And when the message comes with the change view. MainViewModel

receives notification and executes the event and does not need to know who sent the message.

And remember that mvvm is just a sample, not a religion ... just use what holds you and you have a template in the back of your head =) ...

+3


source


Your view models shouldn't have any reference to the view, ideally. If you are doing MVVM you really need to use the MVVM framework . What you are describing appears to be a ViewModel that holds two other ViewModels.

Personally, I would not use the event aggregator if only one user was interested in the message (in this case, the parent's main view model). You can simply use regular .NET events and apply the standard event pattern if you need loose coupling.



Your main view model will contain links to the two child vision models and subscribe to their event that the switch triggers. When a button is clicked on child 1, it raises its event and the main view model then switches the current view in its event handler to the child.

It's very easy using an MVVM framework like Caliburn.Micro . Your main view model will be of type Conductor

and then you just change ActiveItem

.

+1


source







All Articles