视图模型之间的WPF MVVM通信

问题描述:

我正在WPF MVVM应用程序上,其中有2个视图View1和View2及其各自的ViewModel.现在,我想在View1中单击一个按钮将关闭View1并使用ViewModel1打开View2. 另外,我想从ViewModel1打开时将某些数据(例如人员类的实例)传递给ViewModel2,这将用于在View2中显示信息.

I am working on WPF MVVM application wherein I have 2 views View1 and View2 with their respective ViewModels. Now, I want on click of a button in View1 would close View1 and open View2 using ViewModel1. Also, I want to pass some data say a instance of person class to ViewModel2 when opening from ViewModel1 which would be used to display information in View2.

仅在ViewModels中实现此目标的最佳方法,可能是最简单的方法,我想避免在后面的代码中编写用于导航的代码.

What is the best and possibly the simplest way to achieve this inside ViewModels only, I would want to avoid writing code for navigation in code behind.

如何使用Mediator模式(例如,请参见 John Smith )还是弱事件? Afaik的几个MVVM框架/库(例如PRISM,Caliburn.Micro,MVVMCross)已经随附了用于这些的基础结构代码. 还有独立于任何特定MVVM框架的独立库,例如加速

How about using the Mediator pattern (for example see technical-recipes.com or John Smith) or weak events? Afaik several MVVM frameworks/libs (like PRISM, Caliburn.Micro, MVVMCross) already come with the infrastructure code for these. There are also separate libraries that are independent of any specific MVVM framework, like Appccelerate EventBroker which can help you achieve something along the lines of what you want.

但是,对于事件,我想知道您是否需要有关事件是否得到正确"处理的一些反馈.有多种方法可以实现此目的(更改事件args的值,处理事件同步,引发事件之后,检查事件args的值),但是它们不像方法的返回值或方法抛出

With events, however, I wonder whether you require some feedback on whether the event was "correctly" handled or not. There are ways to achieve this (altering the value of the event args, handling the events sync, after raising the event, checking the value of the event args), but they are not as concise as a method's return value or a method throwing an exception.

对不起,我刚刚意识到第二个View/ViewModel尚未打开.因此,我的解决方案"不(简单地)适用.您需要在视图模型树中传递指令"up",甚至可能传递给根,您可以在其中实例化并显示新的视图模型(在新窗口中显示还是在现有视图中作为ContentControl?)

sorry I just realized that the second view/ViewModel is not open, yet. So my "solution" is not (that simply) applicable. You need to pass the instruction "up" in the view model tree, maybe even to the root, where you can instantiate and show the new view model (show in a new window or as a ContentControl in an existing view?)