如何在WPF中使用一次性视图模型?
如果视图模型引用非托管资源或具有事件处理程序(例如调度程序计时器上的处理已过期),如何确保视图模型得到正确处理。在第一种情况下,终结器是一种选择,虽然并不理想,但在后者中,它永远不会被调用。我们如何判断何时不再有视图附加到视图模型。
How do I ensure view models are properly disposed of if they reference unmanaged resources or have event handlers such as handling elapsed on a dispatcher timer. In the first case, a finaliser is an option, although not ideal, but in the latter, it will never be called. How can we tell when there is no longer a view attached to the view model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通过执行以下操作来完成此操作:
定义我的应用程序类如下:
I accomplished this by doing the following:
Defining my App class as follows:
一种可能但不是完美的解决方案:
在视图模型上实现 IDisposable,然后在视图的构造函数中使用此扩展方法。
One possible, although not perfect solution:
Implement IDisposable on the View Model, then use this extension method in the constructor of the view.
您应该在视图卸载或应用程序关闭时处置视图模型。 现有答案采用这种方法,但不处理卸载后再次加载视图的情况。如果这是您需要处理的场景,那么您还需要在重新加载视图时重新创建数据上下文。
如果您经常使用此模式,它也可以轻松地移动到您可以从视图构造函数调用的扩展方法中:
You should dispose the view model when the view is Unloaded or when the application is shutting down. The existing answer takes this approach, but doesn't handle the case where the view is loaded again after being unloaded. If that is a scenario you need to handle, you will also need to re-create the data context when the view is re-loaded.
If you use this pattern a lot, it could also be easily moved into an extension method that you can call from the view constructor: