处理 WPF 用户控件 [英] Disposing WPF User Controls

查看:39
本文介绍了处理 WPF 用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个供第三方使用的自定义 WPF 用户控件.我的控件有一个私有成员,它是一次性的,我想确保一旦包含窗口/应用程序关闭,它的 dispose 方法将始终被调用.但是,UserControl 不是一次性的.

I have created a custom WPF user control which is intended to be used by a third party. My control has a private member which is disposable, and I would like to ensure that its dispose method will always get called once the containing window/application is closed. However, UserControl is not disposable.

我尝试实现 IDisposable 接口并订阅 Unloaded 事件,但在宿主应用程序关闭时两者都没有被调用.MSDN 说可能根本不会引发 Unloaded 事件.并且它也可能被触发多次,即用户更改主题时.

I tried implementing the IDisposable interface and subscribing to the Unloaded event but neither get called when the host application closes. MSDN says that the Unloaded event may not be raised at all. And it might also be triggered more than once, that is when user changes theme.

如果可能的话,我不想依赖我的控件的使用者记得调用特定的 Dispose 方法.

If at all possible, I don't want to rely on consumers of my control remembering to call a specific Dispose method.

 public partial class MyWpfControl : UserControl
 {
     SomeDisposableObject x;

     // where does this code go?
     void Somewhere() 
     {
         if (x != null)
         {
             x.Dispose();
             x = null;
         }

     }
 }

到目前为止,我找到的唯一解决方案是订阅 Dispatcher 的 ShutdownStarted 事件.这是一个合理的方法吗?

The only solution I have found so far is to subscribe to the Dispatcher's ShutdownStarted event. Is this a reasonable approach?

this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;

推荐答案

有趣的博客文章在这里:处理 WPF UserControl (ish)

Interesting blog post here: Dispose of a WPF UserControl (ish)

它提到订阅 Dispatcher.ShutdownStarted 处置您的资源.

It mentions subscribing to Dispatcher.ShutdownStarted to dispose of your resources.

这篇关于处理 WPF 用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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