从另一个视图模型更新一个视图模型 [英] Updating a viewmodel from another viewmodel

查看:107
本文介绍了从另一个视图模型更新一个视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个ViewModels,一个连接到主窗口,另一个连接到子窗口,通过单击主窗口上的按钮可以打开子窗口.子窗口包含一个项目列表,我想选择一个项目并通过更新主窗口viewmodel在主窗口中显示它.做到这一点的最佳方法是什么.谢谢!

I have two ViewModels one is attached to a main window and the other is attached to child window that is opened by clicking on a button on the main window. The child window contains a list of items and I want to select an item and display it in the main window by updating the main window viewmodel. What is the best way to accomplish this. Thanks!

推荐答案

有许多方法可以做到这一点.

There are any number of ways to do this.

  • 将对主/父视图模型的引用传递给子视图,并让子视图调用主视图模型.

  • Pass a reference to the main/parent view model into the child and have the child call the main view model.

让子视图模型触发父级订阅的事件.

Have the child view model fire an event that the parent subscribes to.

使用信使/调解器在两者之​​间进行通信.父母订阅,孩子发布消息.这提供了松散的耦合.

Use a messenger/mediator to communicate between the two. The parent subscribes, the child posts the message. This provides loose coupling.

将主视图模型设置为全局服务.以某种方式注册.让孩子查找服务(要求全局服务是一个很常见的问题),然后在全局/通用接口上调用某些东西.

Set the main view model up as a global service. Register it somehow. Have the child look up the service (requiring global services is a pretty common problem) and then call something on the global/common interface.

根据我的经验,最简单的方法是#2.在子视图模型上定义一个事件.父级将不得不查找子级(我不知道它是否包含该子级,或者您的视图模型是如何构造的)并订阅该事件.

From my experience, the simplest method would be #2. Define an event on the child view model. The parent will have to look up the child (I don't know if it contains it or how your view models are constructed) and subscribe to the event.

这篇关于从另一个视图模型更新一个视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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