Registering for messages outside of a ViewModel in MVVM Light?
I was trying to register for a message outside of a ViewModel in a static constructor but apparently that registration didn't take: the registered action never ran when messages were sent. I tried passing in null or a new object for the recipient
parameter when registering but that didn't work.
I have a feeling the 开发者_Go百科specifying the recipient must be important somehow, but I don't know why. I thought that all recipients were supposed to get broadcasted messages anyway. Is there a way to make this work or is this simply not supported?
The recipient is important when you use Messenger.Register
for Messenger.Send
it is not important. However, there is a known bug in the WeakReference
WeakAction
implementation in MVVM that holds a reference to the recipient, although, it should release it.
In short, if you are inside a ViewModel, make sure that you call Cleanup
. In a view, call Messenger.Unregister(this)
in the Unloaded
event e.g.
public MyView() {
this.Unloaded += (o, e) => { Messenger.Unregister(this); }
}
In other classes your will have to either implement IDisposable
or use some other mechanism to unregister the message recipient.
See also:
- MVVM Light Listener not releasing / deterministic finalization for registered object?
- Does mvvm light v3 unregister work properly?
- When to dispose ViewModel in MVVM Light
Nevermind, I went into the source code and figured out what was happening. It's adding the recipient as a WeakReference to figure out if it's alive or not. I was just passing in new object()
as the recipient and it wasn't firing because it thought my recipient was dead.
精彩评论