视图模型之间的 WPF MVVM 通信 [英] WPF MVVM communication between View Model

查看:42
本文介绍了视图模型之间的 WPF MVVM 通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 WPF MVVM 应用程序,其中我有 2 个视图 View1 和 View2,以及它们各自的 ViewModel.现在,我想单击 View1 中的按钮将关闭 View1 并使用 ViewModel1 打开 View2.另外,我想在从 ViewModel1 打开时将一些数据(例如 person 类的实例)传递给 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 模式(例如参见 technical-recipes.comJohn Smith) 还是弱事件?Afaik 几个 MVVM 框架/库(如 PRISM、Caliburn.Micro、MVVMCross)已经带有这些基础设施代码.还有独立于任何特定 MVVM 框架的独立库,例如 Appccelerate EventBroker 它可以帮助您实现您想要的东西.

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.

抱歉,我刚刚意识到第二个视图/ViewModel 尚未打开.所以我的解决方案"并不(那么简单)适用.您需要在视图模型树中传递向上"指令,甚至可能传递到根,在那里您可以实例化并显示新的视图模型(在新窗口中显示或作为现有视图中的 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?)

这篇关于视图模型之间的 WPF MVVM 通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆