处置WPF用户控件 [英] Disposing WPF User Controls
问题描述
我已创建自定义WPF用户控制,其目的是用于由第三方。我控制了这是一次性的私有成员,我想,以确保其Dispose方法总是会被调用一次,包含窗口/关闭应用程序。但是,用户控件不是一次性的。我试图实现IDisposable接口和订阅卸载的事件,但没有得到主机的应用程序关闭时调用。如果可能的话,我不想依靠消费者我的控制记住调用特定的Dispose方法。
公共部分类MyWpfControl:用户控件
{
SomeDisposableObject X;
//其中,这是否code去了?
无效某处()
{
如果(X!= NULL)
{
x.Dispose();
X =零;
}
}
}
我已经发现迄今唯一的解决办法是订阅分派器的ShutdownStarted事件。这是一个合理的方法?
this.Dispatcher.ShutdownStarted + = Dispatcher_ShutdownStarted;
在这里有趣的博客文章:
<一个href="http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx">http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx
它提到订阅<一个href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.shutdownstarted.aspx">Dispatcher_ShutDownStarted处置你的资源。
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. I tried implementing the IDisposable interface and subscribing to the Unloaded event but neither get called when the host application closes. 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;
}
}
}
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;
Interesting blog post here:
http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx
It mentions subscribing to Dispatcher_ShutDownStarted to dispose of your resources.
这篇关于处置WPF用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!