Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicate two view models in WPF MVVM [closed]

Tags:

c#

mvvm

wpf

I am developing a WPF application and I have some problems to communicate one view model with another.

I have:

  1. MainViewModel
  2. ChildViewModel1
  3. ChildViewModel2

Every time a property changes in MainViewModel, ChildViewModel1 and ChildViewModel2 should get notified.

Can anyone suggest a workaround?

EDIT: I am thinking in a solution descrided MVVM Light (http://simplemvvmtoolkit.codeplex.com/SourceControl/changeset/view/23821#313594.), that is implementing a message bus. Is it the right approach?

like image 815
guilhermecgs Avatar asked Apr 22 '13 14:04

guilhermecgs


3 Answers

the common way for viewmodels to communicate between themselves is implimentation of theMediator design pattern

here is how it is done in MVVMLight http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/27aaefff-e463-451c-87d9-37367a343e0e

in Prism is: http://blogs.u2u.be/diederik/post/2011/01/15/Using-the-Prism-40-Event-Aggregator.aspx

in Caliburn is: http://www.mindscapehq.com/blog/index.php/2012/02/01/caliburn-micro-part-4-the-event-aggregator/

like image 160
Nahum Avatar answered Nov 12 '22 08:11

Nahum


In most cases I would NOT suggest using any centralized place to share "events"/"notifications", like EventAggregator, etc.. This leads to later issues related with not clear relations between ViewModels. Such notifications makes sense in very specific cases when relations between listener/publisher is not known even on design stage. I would suggest draw simple diagram with relations between ViewModels and find a way of using standard .NET events, so when you have clear realtionships between ViewModels like ViewModel1 has a reference to ViewModel2 so can subscribe to an event or provide own callback, so it will be easy to build such event notifications.

like image 12
sll Avatar answered Nov 12 '22 10:11

sll


I would use a IService that is implemented by each view model. Then in the view models you can pass the service properties to properties of the view model that implement INotifypropertychanged. For example, I have a service called INavigationService that is implemented by my view models and it has properties like CanNavigate, currentView etc that I bind to in my view models. Changes to these properties can cause navigation or change properties that other view models are binding to.

like image 3
J King Avatar answered Nov 12 '22 09:11

J King