MVVM - 用户控件相互交谈的理想方式是什么 [英] MVVM - what is the ideal way for usercontrols to talk to each other

查看:19
本文介绍了MVVM - 用户控件相互交谈的理想方式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含其他几个用户控件的用户控件.我正在使用 MVVM.每个用户控件都有一个对应的 VM.这些用户控件如何相互发送信息?我想避免在后面的 xaml 代码中编写任何代码.特别是我对控件(在主用户控件内部)如何相互通信以及它们如何与容器用户控件通信感兴趣.

I have a a user control which contains several other user controls. I am using MVVM. Each user control has a corresponding VM. How do these user controls send information to each other? I want to avoid writing any code in the xaml code behind. Particularly I am interested in how the controls (inside the main user control) will talk to each other and how will they talk to the container user control.

编辑:我知道使用 events-delegates 将帮助我解决这个问题.但是,我想避免在 xaml 代码隐藏中编写任何代码.

EDIT: I know that using events-delegates will help me solve this issue. But, I want to avoid writing any code in xaml code-behind.

推荐答案

通常情况下,最好尽量减少部件之间的通信量,因为每次两个用户控件相互交谈"时,你就引入了一个它们之间的依赖关系.

Typically, it's best to try to reduce the amount of communication between parts, as each time two user controls "talk" to each other, you're introducing a dependency between them.

话虽如此,有几点需要考虑:

That being said, there are a couple of things to consider:

  • 用户控件始终可以通过公开属性和使用 DataBinding 与其包含的控件对话".这非常好,因为它在各个方面都保留了 MVVM 风格.
  • 包含的控件可以使用属性将两个用户控件上的两个属性链接"在一起,再次保持清晰的边界

如果您确实需要更明确的沟通,有两种主要方法.

If you do need to have more explicit communication, there are two main approachs.

  1. 实现两个元素共有的服务,并使用依赖注入在运行时提供实现.这让控件可以与服务通信,而服务又可以使控件保持同步,但也可以将依赖关系降至最低.
  2. 使用某种形式的消息传递控件之间的消息.许多 MVVM 框架采用这种方法,因为它将发送消息与接收消息分离,再次将依赖关系保持在最低限度.

这篇关于MVVM - 用户控件相互交谈的理想方式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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