MVVM - what is the ideal way for usercontrols to talk to each other

后端 未结 9 1309
失恋的感觉
失恋的感觉 2020-12-08 05:24

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

9条回答
  •  忘掉有多难
    2020-12-08 06:03

    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:

    • UserControls can always "talk" to their containing control via exposing properties and using DataBinding. This is very nice, since it preserves the MVVM style in all aspects.
    • The containing control can use properties to "link" two properties on two user controls together, again, preserving clean boundaries

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

    1. Implement a service common to both elements, and use Dependency Injection to provide the implementation at runtime. This lets the controls talk to the service, which can in turn, keep the controls synchronized, but also keeps the dependency to a minimum.
    2. Use some form of messaging to pass messages between controls. Many MVVM frameworks take this approach, as it decouples sending the message from receiving the message, again, keeping the dependencies to a minimum.

提交回复
热议问题