MVVM Messaging vs RaisePropertyChanged<T>

ぃ、小莉子 提交于 2020-01-04 02:39:09

问题


  1. What is the difference between MVVM messaging and RaisePropertyChanged.

  2. I'm trying to run a function in View model A when a property in view model B changes, which approach is a better one to use - Messaging or RaisePropertyChanged broadcast?

Thanks, Nikhil


回答1:


  1. Messaging decouples your view models. It's like a Tweet, you send out a message into the air and someone can read it or someone could register to listen for it. PropertyChanged is used by the UI to know that something changed and to redraw the values.

  2. Messaging is definitely the best choice. MVVM light has a built in option to broadcast the message. You can use the mvvminpc code snippet.

It's surprising your post wasn't answered sooner. Maybe this answer will still be useful to someone out there.




回答2:


To follow @Kevin's post:

Messages are indeed used for decoupled comunication. This means that once the message is sent one or more recipients - who have registered their interest in a particular message type - are notified.

In general I use INotifyPropertyChanged when the comunication between the view and the view-model is concerned (via databinding) and messages when I want to communicate between multiple view models or upward from the view-model to the view and databinding is not concerned.

When receiving messages in the view model make sure that you call Cleanup to unregister from the Messenger. If you handle the message in the view - where no Cleanup is available - register for the Unloaded event and call Messenger.Unregister(this) from there.




回答3:


Messaging should be used when it is solving a specific problem. If you uses it everywhere your application becomes difficult to maintain and later understand the code.




回答4:


Depends on how View model A and View model B relate to each other.

If View Model A already has direct reference to B for a valid reason (e.g. A "owns" B i.e. it is parent-child relationship) then just subscribe to B.PropertyChanged event. That way B doesn't need to remember that something depends on it which is in spirit of reactive programming. (offtopic: in case if B has longer lifetime than A then don't forget to unsubscribe from event because "long living publisher / short living subscriber" can result in memory leaks).

If A and B are unrelated / in very different parts of the app then messaging might be a better choice.



来源:https://stackoverflow.com/questions/5982639/mvvm-messaging-vs-raisepropertychangedt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!