What is the difference between MVVM messaging and RaisePropertyChanged.
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开发者_JS百科 or RaisePropertyChanged broadcast?
Thanks, Nikhil
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.
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.
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.
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.
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.
精彩评论