Wpf动画OnCloseing导致火灾Close事件两次



我的应用程序窗口使用一个基本窗口类。

  • BaseWindow
  • MainWindow

现在,我在BaseWindow类的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方法。基本窗口的OnClosing可以具有与AnimationWindowBase_Closing方法相同的代码。但在主窗口中,你可以这样做:

protected override void OnClosing(CancelEventArgs e)
{
    base.OnClosing(e);
    if (!e.Cancel)
        AppConfigs.SaveAll();
}

最新更新