简体   繁体   English

mvvmlight 信使奇怪的行为

[英]mvvmlight messenger strange behaviour

I have a strange behavior in my project.我的项目中有一个奇怪的行为。 I use MvvmLight messenger to notify different parts of my UI to update.我使用 MvvmLight messenger 来通知我 UI 的不同部分进行更新。

   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.当我在注册后看到 Messenger 内容时,它包含大约 400 个 CardUpdateMessage 的注册操作,但是当我调用 send 时,它们都没有触发。 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.更新:我用调试器做了一些研究,发现在文件https://mvvmlight.codeplex.com/SourceControl/latest#GalaSoft.MvvmLight/GalaSoft.MvvmLight (PCL)/Messaging/Messenger.cs 中的方法 SendToList 被触发并在它的内部循环 WeakAction 被触发,但 Refresh 方法没有运行。 Does it something I haven't suspected with WeakAction?这是我对 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.由于意外行为,不允许在 Messenger.Register 中使用匿名函数。 just Messenger.Default.Register(this, this._entry.Id, Refresh);只是Messenger.Default.Register(this, this._entry.Id, Refresh); and private void Refresh(CardUpdateMessage msg) ...private void Refresh(CardUpdateMessage msg) ...

External reference : https://mvvmlight.codeplex.com/workitem/7640外部参考https : //mvvmlight.codeplex.com/workitem/7640

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这是答案https://mvvmlight.codeplex.com/workitem/7640和这个奇怪的行为,在 MVVM light Messenger 中有动作、局部变量和垃圾收集

Solution in short words - do no use lambdas in Messenger.Default.Register, because the can behave not as you expected.简而言之,解决方案 - 不要在 Messenger.Default.Register 中使用 lambda,因为它的行为可能与您预期的不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM