如何使用一次性视图模型在WPF?

编程入门 行业动态 更新时间:2024-10-24 22:19:29
本文介绍了如何使用一次性视图模型在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?

本文发布于:2023-10-23 22:38:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   如何使用   模型   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!