如何使用一次性视图模型在WPF? [英] How to use disposable view models in WPF?
本文介绍了如何使用一次性视图模型在WPF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何确保视图模型被妥善处置,如果他们引用非托管资源或有事件处理程序,如处理上的调度计时器已过。在第一种情况下,一个finaliser是一种选择,虽然不是理想的,但在后者中,它永远不会被调用。我们怎样才能知道什么时候不再有连接到视图模型视图
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.
推荐答案
一种可能,虽然不是完美的解决方案:
One possible, although not perfect solution:
在视图模型实现IDisposable,然后使用这个扩展方法在视图的构造函数。
Implement IDisposable on the View Model, then use this extension method in the constructor of the view.
public static void HandleDisposableViewModel(this FrameworkElement Element)
{
Action Dispose = () =>
{
var DataContext = Element.DataContext as IDisposable;
if (DataContext != null)
{
DataContext.Dispose();
}
};
Element.Unloaded += (s, ea) => Dispose();
Element.Dispatcher.ShutdownStarted += (s, ea) => Dispose();
}
这篇关于如何使用一次性视图模型在WPF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文