何时在 MVVM Light 中处置 ViewModel
我正在考虑开始使用 MVVM Light,并且遇到了“新”ICleanup 界面。我只是想知道当您离开该页面时,您什么时候会清理虚拟机?
另外,我看到 ViewModelLocator 中有一个主要清理功能,它应该清理所有虚拟机......什么时候使用它?
非常感谢
问候, 毛罗
I'm looking into getting started using MVVM Light, and I came across the "new" ICleanup interface. I was just wondering when would you cleanup the VM...when you navigate away from the page?
Also, I see there is a Main Cleanup in the ViewModelLocator which should cleanup all the VM's...when would this be used?
Thanks very much
Regards,
Mauro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 Laurent 所说,
ICleanup
接口相对于IDispose
实现(以前存在)的优势在于,您可以更频繁地调用它,而无需将 VM 标记为处置。这意味着,只要您想要/需要取消注册 VM 的消息处理,就应该调用ICleanup.Cleanup
。显然,在这种情况下,您需要有一种方法可以在稍后需要时再次注册所有消息处理程序。就我个人而言,我更喜欢用
IDispose
方式处理 VM 清理,特别是因为我倾向于 IOC 容器。但是,我可以看到 Laurent 的案例,并且在虚拟机上实现调用Cleanup
的 IDisposable 并不是什么诡计。一般来说,处置/清理虚拟机的时间点取决于它的实例化方式和对象的生命周期。这些决定取决于您的应用程序的设计,并且没有明确的指导来指导您何时应该这样做。但请记住,只要您在视图模型中注册消息处理程序,就必须执行此操作 - 在其他情况下,并非严格需要执行此操作。
在谈论消息处理程序时,当您在视图中注册了消息处理程序时,不要忘记在视图中取消注册它们(请参阅这篇文章)。 - 再考虑一下,我将把代码放在这里以使其清晰并供将来参考:
在代码隐藏文件中的视图构造函数中添加以下代码,以确保卸载视图时释放已注册的消息处理程序:
The advantage of the
ICleanup
interface over theIDispose
implementation (that was previously there) is - as Laurent states it - that you can call it more frequently and without marking the VM as disposed. This means, you should callICleanup.Cleanup
whenever you want/need to unregister the message handling for your VM. Obviously in this case you need to have a method that register all message handlers again when you need them later.Personally, I'm more a friend of the
IDispose
way of dealing with VM cleanup, especially as I are inclined to IOC containers. But, I can see Laurent's case and implementingIDisposable
callingCleanup
on a VM is no trickery.In general, the point in time when you dispose/cleanup a VM depends on how it is instantiated and the lifespan of the object. These decisions are governed by the desing of your application and there is no clear guidance to when you should do it. But keep in mind that it has to be done whenever you registered a message handler within your view model - in other cases it is not strictly needed.
And while talking about message handlers, don't forget to de-register them in your views as well when you have registered a message handler there (see this post). - On second thoughts, I'll put the code here to make it clear and for future reference:
In your view's constructor in the code behind file add the following code to ensure that the registered message handlers are released when the view is unloaded: