【问题标题】:mvvmlight messenger strange behaviourmvvmlight messenger 奇怪的行为
【发布时间】:2016-10-07 07:08:59
【问题描述】:

我的项目中有一个奇怪的行为。我使用 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(); );   
 }

并用

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

当我在注册后看到 Messenger 内容时,它包含大约 400 个已注册的 CardUpdateMessage 操作,但是当我调用 send 时,它们都没有触发。 顺便说一句,每个消息类型具有单个注册对象的类似代码可以按我的预期工作。这个问题的原因是什么?

更新:我对调试器进行了一些研究,发现在文件https://mvvmlight.codeplex.com/SourceControl/latest#GalaSoft.MvvmLight/GalaSoft.MvvmLight (PCL)/Messaging/Messenger.cs 方法中 SendToList 被触发,并且在其内部循环中 WeakAction 被触发,但是刷新方法未运行。 WeakAction 是我没有怀疑的吗?

解决方案:我找到了这个问题的案例。由于意外行为,不允许在 Messenger.Register 中使用匿名函数。 只是Messenger.Default.Register(this, this._entry.Id, Refresh);private void Refresh(CardUpdateMessage msg) ...

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

【问题讨论】:

  • 很高兴您找到了解决方案,但您不应将其编辑到您的问题中。只需在下面添加您找到的答案,在所需的等待期后,您可以将其选为正确并关闭它。这可能看起来很奇怪,但我们就是这样做的。
  • @Will 好的,我已经写好了答案

标签: c# wpf mvvm mvvm-light


【解决方案1】:

这是答案https://mvvmlight.codeplex.com/workitem/7640 和这个 Strange behavior with actions, local variables and garbage collection in MVVM light Messenger

简短的解决方案 - 不要在 Messenger.Default.Register 中使用 lambda,因为它的行为可能与您预期的不同。

【讨论】:

  • 不幸的是,3 年后,第一个链接断开了。
猜你喜欢
  • 2014-06-25
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多