Communicate two view models in WPF MVVM [closed]

2020-02-05 04:08发布

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?

标签: c# wpf mvvm
3条回答
欢心
2楼-- · 2020-02-05 04:19
ゆ 、 Hurt°
3楼-- · 2020-02-05 04:22

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.

查看更多
乱世女痞
4楼-- · 2020-02-05 04:33

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.

查看更多
登录 后发表回答