我创建了一个自定义WPF用户控件,供第三方使用.我的控件有一个一次性的私有成员,我想确保一旦包含窗口/应用程序关闭,它的dispose方法将始终被调用.但是,UserControl不是一次性的.我尝试实现IDisposable接口并订阅Unloaded事件,但在主机应用程序关闭时都不会被调用.如果可能的话,我不想依赖我控制的消费者记住调用特定的Dispose方法.
public partial class MyWpfControl : UserControl
{
SomeDisposableObject x;
// where does this code go?
void Somewhere()
{
if (x != null)
{
x.Dispose();
x = null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我找到的唯一解决方案是订阅Dispatcher的ShutdownStarted事件.这是一种合理的方法吗?
this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
Run Code Online (Sandbox Code Playgroud) 我有一个在XAML中定义的动画(作为UserControl),它实际上每秒在两个图像之间切换:
<UserControl x:Class="KaleidoscopeApplication.Controls.RemoteAnimation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="RemoteAnimation_Loaded"
Unloaded="RemoteAnimation_Unloaded">
<Grid Canvas.Left="500" Canvas.Top="84">
<Grid.Triggers>
<EventTrigger RoutedEvent="Grid.Loaded">
<BeginStoryboard>
<Storyboard x:Name="storyboard" RepeatBehavior="Forever">
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="remote2" BeginTime="00:00:00" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0:0:1">
<DiscreteObjectKeyFrame.Value>
<Visibility>Collapsed</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:2">
<DiscreteObjectKeyFrame.Value>
<Visibility>Visible</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
<Image Name="remote1" Source="/Resources/Elements/Images/341.png"/>
<Image Name="remote2" Source="/Resources/Elements/Images/342.png"/>
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
它可以在窗口中使用:
<!-- Remote -->
<uControl:RemoteAnimation
x:Name="remoteAnimation"
Canvas.Left="316" Canvas.Top="156" Height="246" Width="121" />
Run Code Online (Sandbox Code Playgroud)
我的问题是,当包含动画的窗口关闭时,它会继续运行并导致泄漏.我无法通过带有storyboard.Stop()的RemoteAnimation_Unloaded()来停止动画......它不会做插孔.
我已经检查了这两个帖子,但它们不适用:
我能够进入卸载方法,但调用Stop()不会停止动画.根据我的理解,对于故事板调用Begin()可能是一个问题.isControlable参数存在重载.但是,由于动画完全在XAML中,我不确定如何影响它.