Registering for messages outside of a ViewModel in MVVM Light?

岁酱吖の 提交于 2019-12-08 01:42:59

问题


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 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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7695045/registering-for-messages-outside-of-a-viewmodel-in-mvvm-light

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