Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM- View Model-View Model Communications

How do I go about having two view models communicate with one another using MVVM Light. I know how to use the messenger class and register etc.. Here is my Scenario

A Settings View ---> a Settings View Model 
                                  .
                                  .
                                  .

A MainPage View ---> A MainPage ViewModel

If something changes in the Settings View it will Message back to the Settings View Model. So then I want the Settings View Model to communicate to the MainPage View Model about what changed. THe MainPage ViewModel will then tell the View.

like image 968
Mike Diaz Avatar asked Mar 19 '10 03:03

Mike Diaz


People also ask

How communication happens in MVVM?

Messages are often packaged into different types, so a ViewModel can subscribe to only listen for specific message types such as CloseApplicationMessages. This kind of loosely coupled event system is ideal for MVVM because the ViewModels don't need to know about each other to be able to do their job.

What is the difference between View and ViewModel?

VIEW: ( Platform Specific Code – USER INTERFACE ) What the user sees, The Formatted data. VIEWMODEL: ( Reusable Code – LOGIC ) Link between Model and View OR It Retrieves data from Model and exposes it to the View. This is the model specifically designed for the View.


2 Answers

A common pattern for this style of problem is Mediator (a class that both view models reference and can be used to pass messages between the two).

The Mediator class has since been moved to the Cinch WPF/SL MVVM Framework, which appears to still be actively developed/supported.

The pattern I prefer is the Event Aggregator, an example can be found in the Prism framework. In this pattern different view models subscribe to events from the aggregator and others publish events.

Hope this helps

like image 62
Nigel Sampson Avatar answered Oct 11 '22 22:10

Nigel Sampson


I second Nigel's suggestion of using the Mediator, take a look at Josh Smith's blog and his implementation of this:

http://joshsmithonwpf.wordpress.com/?s=mediator

At the bottom you can download the Mediator Prototype and Demo, just remember to rename it from .doc to a .zip.

Hope this helps...

like image 36
Richard Avatar answered Oct 11 '22 22:10

Richard