mvvmlight messenger strange behaviour

寵の児 提交于 2019-12-23 01:26:22

问题


I have a strange behavior in my project. I use MvvmLight messenger to notify different parts of my UI to update.

   public EntryViewModel(MenuViewModel menuVM, Entry item)
    {
        this._menuVM = menuVM;
        OpenDetailsCommand = new RelayCommand(OpenDetailsInMainWindow);
        BackCommand = new RelayCommand(Back);

        this._entry = item;
        Refresh(); 

        Messenger.Default.Register<CardUpdateMessage>(this, this._entry.Id, msg => Refresh(); );   
 }

and send with

Messenger.Default.Send(new CardUpdateMessage(id), id);

when I see Messenger content after registration it contains about 400 registered actions of CardUpdateMessage, but when I call send none of them fires. By the way, similar code with single registered object per Message type work as I expect. What is the cause of this problem?

Update: I have made some research with debugger and found that in file https://mvvmlight.codeplex.com/SourceControl/latest#GalaSoft.MvvmLight/GalaSoft.MvvmLight (PCL)/Messaging/Messenger.cs method SendToList is fired and in its inner loop WeakAction is fired, but Refresh method is not run. Does it something I haven't suspected with WeakAction?

Solution: I have found the case of this issue. It's NOT ALLOWED to use anonimous function in Messenger.Register due to unexpected behavior. just Messenger.Default.Register(this, this._entry.Id, Refresh); and private void Refresh(CardUpdateMessage msg) ...

External reference: https://mvvmlight.codeplex.com/workitem/7640


回答1:


This is the answer https://mvvmlight.codeplex.com/workitem/7640 and this Strange behavior with actions, local variables and garbage collection in MVVM light Messenger

Solution in short words - do no use lambdas in Messenger.Default.Register, because the can behave not as you expected.



来源:https://stackoverflow.com/questions/39911423/mvvmlight-messenger-strange-behaviour

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