C# 在 WPF MVVM 中交流两个视图模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16149146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:09:13  来源:igfitidea点击:

Communicate two view models in WPF MVVM

c#wpfmvvm

提问by guilhermecgs

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

我正在开发一个 WPF 应用程序,但在将一个视图模型与另一个视图模型进行通信时遇到了一些问题。

I have:

我有:

  1. MainViewModel
  2. ChildViewModel1
  3. ChildViewModel2
  1. 主视图模型
  2. 子视图模型1
  3. 子视图模型2

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

每次 MainViewModel 中的属性更改时,都应通知 ChildViewModel1 和 ChildViewModel2。

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?

编辑:我正在考虑一个描述 MVVM Light ( http://simplemvvmtoolkit.codeplex.com/SourceControl/changeset/view/23821#313594.)的解决方案,即实现消息总线。这是正确的方法吗?

回答by J King

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.

我将使用由每个视图模型实现的 IService。然后在视图模型中,您可以将服务属性传递给实现 INotifypropertychanged 的​​视图模型的属性。例如,我有一个名为 INavigationService 的服务,它由我的视图模型实现,它具有我绑定到我的视图模型中的 CanNavigate、currentView 等属性。对这些属性的更改可能会导致导航或更改其他视图模型绑定到的属性。

回答by sll

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.

在大多数情况下,我不建议使用任何集中的地方来共享“事件”/“通知”,例如 EventAggregator 等。这会导致与 ViewModel 之间关系不明确的后续问题。在非常特殊的情况下,即使在设计阶段也不知道侦听器/发布者之间的关系,这种通知是有意义的。我建议用 ViewModels 之间的关系绘制简单的图表并找到一种使用标准 .NET 事件的方法,所以当你在 ViewModels 之间有明确的关系时,比如 ViewModel1 有一个对 ViewModel2 的引用,所以可以订阅一个事件或提供自己的回调,所以它会易于构建此类事件通知。