I am developing a WPF application and I have some problems to communicate one view model with another.
I have:
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?
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/
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With