Silverlight - 使用命令在 MVVM 中的 2 个视图模型之间进行通信 [英] silverlight - communicate between 2 view models in MVVM using commands

查看:52
本文介绍了Silverlight - 使用命令在 MVVM 中的 2 个视图模型之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 MVVM 并在 Silverlight(DelegateEvent 和 ICommand)中使用命令

i am working on MVVM and using commanding in silverlight(DelegateEvent and ICommand)

我想要这样的东西,(比如说)我有 2 个用户控件,父控件和子控件.

I want something like this ,(say) i have 2 usercontrols , parent and child .

父母正在托管孩子,他们都有自己的视图模型.

Parent is hosting the child , both have thier own viewmodels .

在父控件上,我有一个按钮,它执行一个简单的命令,在执行该命令时,我想更新子控件文本框中的文本.我们也应该能够改变孩子中可以传播给父母的东西.

On parent i have a button and it executes a simple command , on execute of that command i want to update text in the child control's textbox . also we should be able to change something in child which can propagate to the parent .

事件是对此的最佳答案,还是我可以通过命令以某种方式更新子项/通知父项.

Is events the best answer for this or i can have commands to update child/notify parent in some way.

推荐答案

有几种方法可以解决这个问题.

There are several ways to go about this.

首先,拥有由其他 ViewModel 组成的 ViewModel 是完全合适的,只要您同意它们以这种方式耦合即可.当您这样做时,他们可以使用常规方法调用相互交谈.

First, it is completely appropriate to have ViewModels that are composed of other ViewModels, as long as you are OK with them being coupled in that way. When you do that, they can just talk to each other using regular method calls.

接下来,您可以稍微解耦并使用事件.没有错.仍然存在 Observer -> Observable 耦合,但它们之间的依赖性较小.

Next, you can decouple a bit and use events. Nothing wrong with that. There is still an Observer -> Observable coupling, but they are less dependent upon each other.

接下来,您可以完全解耦并使用 EventAggregator 之类的东西(Prism 有一个很好的可以使用).拍摄 a 发布消息.另一个订阅.他们根本不了解对方.

Next, you can completely decouple and use something like an EventAggregator (Prism has a good one you can use). Shoot a Publish a message. The other subscribes. They don't know about each other at all.

我也为此使用了命令......但是对于 ViewModel 到 ViewModel 的通信,我觉得这有点尴尬.

I have used commands for this as well... but for ViewModel to ViewModel communication, I find this to be a bit awkward.

这篇关于Silverlight - 使用命令在 MVVM 中的 2 个视图模型之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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