Wpf 动画 OnCloseing 导致触发 Close 事件两次
Wpf animation OnCloseing cause fire Close event two time
我的应用程序 windows.
使用基础 window class
BaseWindow
MainWindow
现在,我在 BaseWindow
class 中的 OnClosing
中编写了一个动画,如下所示:
void AnimationWindowBase_Closing(object sender, EventArgs e)
{
if (!CloseAnimationIsDone)
{
((CancelEventArgs) e).Cancel = true;
var closeAnimation1 = new DoubleAnimation
{
From = RestoreBounds.Top,
To = RestoreBounds.Top + 10,
Duration = new Duration(TimeSpan.FromMilliseconds(500))
};
closeAnimation1.Completed += (s, eArgs) =>
{
CloseAnimationIsDone = true;
// This line cause fire close again in MainWindow class
Close();
};
BeginAnimation(TopProperty, closeAnimation1);
BeginAnimation(OpacityProperty, new DoubleAnimation
{
From = 1,
To = 0,
Duration = new Duration(TimeSpan.FromMilliseconds(500))
});
}
}
但是如果我在 MainWindow
中有一个 OnClosing
方法,就像这样:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
AppConfigs.SaveAll();
}
然后设置将被保存2次!
有什么好的方法可以解决吗?
不要订阅 Closing
事件,而是尝试覆盖 OnClosing
方法。基础 window 的 OnClosing
可以与您的 AnimationWindowBase_Closing
方法具有相同的代码。但在主要 window 你可以这样做:
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (!e.Cancel)
AppConfigs.SaveAll();
}
我的应用程序 windows.
使用基础 window classBaseWindow
MainWindow
现在,我在 BaseWindow
class 中的 OnClosing
中编写了一个动画,如下所示:
void AnimationWindowBase_Closing(object sender, EventArgs e)
{
if (!CloseAnimationIsDone)
{
((CancelEventArgs) e).Cancel = true;
var closeAnimation1 = new DoubleAnimation
{
From = RestoreBounds.Top,
To = RestoreBounds.Top + 10,
Duration = new Duration(TimeSpan.FromMilliseconds(500))
};
closeAnimation1.Completed += (s, eArgs) =>
{
CloseAnimationIsDone = true;
// This line cause fire close again in MainWindow class
Close();
};
BeginAnimation(TopProperty, closeAnimation1);
BeginAnimation(OpacityProperty, new DoubleAnimation
{
From = 1,
To = 0,
Duration = new Duration(TimeSpan.FromMilliseconds(500))
});
}
}
但是如果我在 MainWindow
中有一个 OnClosing
方法,就像这样:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
AppConfigs.SaveAll();
}
然后设置将被保存2次!
有什么好的方法可以解决吗?
不要订阅 Closing
事件,而是尝试覆盖 OnClosing
方法。基础 window 的 OnClosing
可以与您的 AnimationWindowBase_Closing
方法具有相同的代码。但在主要 window 你可以这样做:
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (!e.Cancel)
AppConfigs.SaveAll();
}