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

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

问题描述

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

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

我们有父视图及其对应的ViewModel,在该视图中,我们选择了项,然后要创建新的子视图(以编辑选择的详细信息),该子视图在XAML中实例化其ViewModel. 当我需要将值传递给Child ViewModel构造函数时,就会发生问题(这是必须从数据库中获取的数据的ID).我假设父级的ViewModel必须与子级的ViewModel进行通信-但无法完成,因为子级的ViewModel直到子级的View在XAML中才被实例化,因此我们无法使用Messenger(MVVM Light Toolkit),而只能从父级的ModelView传播该信息,因为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模式的主要租户之一是,您应该能够在没有View的情况下执行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(您正在努力连接).可以在无头模式下工作吗?在我看来,您是依靠View来执行此父子导航.

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,则ViewModels之间的通信不再有问题. 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天全站免登陆