何时在MVVM Light中放置ViewModel [英] When to dispose ViewModel in MVVM Light

查看:77
本文介绍了何时在MVVM Light中放置ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑开始使用MVVM Light,并且遇到了新的" ICleanup界面.我只是想知道当您离开页面时,何时清理虚拟机...

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?

此外,我看到ViewModelLocator中有一个Main Cleanup,应该清理所有VM ...何时使用它?

Also, I see there is a Main Cleanup in the ViewModelLocator which should cleanup all the VM's...when would this be used?

非常感谢

关于, 毛罗(Mauro)

Regards, Mauro

推荐答案

ICleanup接口相对于IDispose实现(先前存在)的优势是-如Laurent所言-您可以对其进行更多调用频繁且未将VM标记为已处置.这意味着,每当您希望/需要注销虚拟机的消息处理时,都应该调用ICleanup.Cleanup.显然,在这种情况下,您需要一种方法,以便以后需要时再次注册所有消息处理程序.

The advantage of the ICleanup interface over the IDispose 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 call ICleanup.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.

就我个人而言,我更是处理VM清理的IDispose方法的朋友,尤其是当我倾向于使用IOC容器时.但是,我可以看到Laurent的情况,并且在VM上实现IDisposable调用Cleanup并不是一件容易的事.

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 implementing IDisposable calling Cleanup on a VM is no trickery.

通常,处置/清理VM的时间点取决于实例化方式和对象的寿命.这些决定由您的应用程序的设计决定,没有明确的指导说明何时.但是请记住,只要在视图模型中注册了消息处理程序,便必须必须完成-在其他情况下,则并非严格要求

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:

public MyView() {
    this.Unloaded += (o, e) => { Messenger.Unregister(this); }
}

这篇关于何时在MVVM Light中放置ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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