MVVM Light Messenger执行多次 [英] MVVM Light Messenger executing multiple times

查看:106
本文介绍了MVVM Light Messenger执行多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM Light,并且正在使用消息在ViewModel之间进行通信,以让ViewModel知道何时可以执行某些操作.我的问题是我注册了一条消息,然后多次收到它.因此,要使我的程序不止执行一次,我必须创建布尔标志以查看它是否已经被接收到.知道为什么会这样做以及如何阻止它吗?

I am using MVVM Light and am using Messages to communicate between ViewModels to let a ViewModel know when it is ok to execute something. My problem is that I register for a message and then it receives it multiple times. so to keep from my program executing something more than once I have to create boolean flags to see if it has already been recieved. Any idea why it does this and how I can stop it?

推荐答案

确保不再需要消息处理程序时,请注销它们. Messenger会保留对已注册方法的引用,这样可以防止对它们进行垃圾回收.

Make sure you unregister your message handlers once you do not need them anymore. The Messenger keeps a reference to the registered methods and this prevents them from being garbage collected.

因此,对于ViewModels:确保完成后调用Cleanup(或实现IDisposable并从此处调用Cleanup).

Therefore, for ViewModels: make sure that you call Cleanup once you done (or implement IDisposable and call Cleanup from there).

对于视图(控件,Windows或类似控件),请致电Messenger.在视图拆除后发生的事件中取消注册,例如卸载事件.

For Views (Controls, Windows, or similar) call Messenger.Unregister in an event that occurs on the teardown of the view, e.g. the Unloaded event.

这是MVVM的已知行为,已经在多个地方进行了讨论.

This is a known behaviour of the MVVM and has been discussed in several places.

这篇关于MVVM Light Messenger执行多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆