MVVM 在视图模型之间传递值 [英] MVVM pass values between view models

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

问题描述

我尝试处理将值从一个 ViewModel 传递到另一个的问题.这是一个例子.

I try to deal with problem of passing value from one ViewModel to another. Here is an example.

我们有父视图及其对应的视图模型,在该视图中我们选择项目,然后我们想要创建新的子视图(以编辑选择的详细信息),它在 XAML 中实例化其视图模型.当我需要将值传递给 Child ViewModel 构造函数时出现问题(它是必须从数据库中获取的数据的 Id).我假设 Parent 的 ViewModel 必须与 Child 的 ViewModel 进行通信 - 但它无法完成,因为 Child 的 ViewModel 在 Child 的 View 在 XAML 中执行此操作之前不会实例化,因此我们不能使用 Messenger(MVVM Light Toolkit)并且仅从 Parent 的 ModelView 传播该信息,因为 Child 的ModelView 无法订阅(注册到该类型的消息).

We have Parent View and its corresponding ViewModel, in that View we select item and then we want to create new Child View (to edit details of selection) which instantiates its ViewModel in XAML. Problem occurs when I need to pass value to the Child ViewModel constructor (it is Id of data that has to be fetched from database). I assume Parent's ViewModel has to communicate with Child's ViewModel - but it cannot be done since Child's ViewModel is not instantiated until Child's View do that in XAML, so we cannot use Messenger (MVVM Light Toolkit) and just propagate that info from Parent's ModelView because Child's ModelView has not been able to subscribe (register to that type of messages).

我不想打破 MVVM 模式,也找不到任何好的解决方案.感谢我能得到的所有帮助.

I do not want to break MVVM pattern, and cannot find any good solution for that. I appreciate for all help I can get.

推荐答案

MVVM 模式的主要租户之一是,您应该能够在没有视图的情况下执行您的 ViewModel 代码,以便对您的 View 逻辑进行单元测试.换言之,理想情况下,您应该能够以无头"模式执行您的应用程序.

One of the main tenants of the MVVM pattern is that you should be able to execute your ViewModel code without a View, in order to unit test your View logic. In othe words, ideally you should be able to execute your application in a 'headless' mode.

在您的示例中,您声明 ParentView 创建了一个 ChildView,而后者又创建了一个 ChildViewModel(您正在努力连接).这可以在无头模式下工作吗?在我看来,您正在依赖您的视图来执行此父子导航.

In your example you state that the ParentView creates a ChildView which in turn creates a ChildViewModel (which you are struggling to connect up). Can this work in headless mode? It seems to me that you are relying on your View to perform this Parent-Child navigation.

如果反过来,让 ParentViewModel 创建 ChildViewModel,则 ViewModel 之间的通信不再有问题.ParentView 需要观察"(即属性更改)以创建新的 ChildViewModel,并相应地构造 ChildView.

If you flip it the other way, have ParentViewModel create ChildViewModel, you no longer have a problem with communication between ViewModels. The ParentView needs to 'watch' (i.e. property change) for the new ChildViewModel being creates, and constructs the ChildView accordingly.

更详细:

  1. ParentView 实例化 ParentVM
  2. 用户以需要孩子的方式进行交互
  3. ParentVM 创建一个 ChildVM,并通过 ChildVM 属性公开它
  4. ParentView 处理产生的 PropertyChanged 事件,创建 ChildView,将其 DataContext 设置为 ChildVM.

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

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