【问题标题】:Closing event fired twice when set the exitButton.IsCancel = True设置 exitButton.IsCancel = True 时触发两次关闭事件
【发布时间】:2012-01-11 04:47:57
【问题描述】:

我意识到当我设置退出按钮属性为 IsCancel = True 时,窗口的 Closing 事件会触发两次。

    private void exitButton_Click(object sender, RoutedEventArgs e)
    {
        // this button was set attribute IsCancel = True.
        Close();          
    }

    private void BaseWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {          
        MessageBox.Show("test"); // this message box will show twice
                                 // when you click on the exit button
        e.Cancel = true;
    }

这是 WPF 的错误吗?有解决办法吗?

Ps:对不起,我忘了说这个错误只发生在你从父窗口调用你的窗口时。

【问题讨论】:

  • 如果您删除 e.Cancel = true 导致窗口实际关闭会怎样?
  • 是的,如果我删除 e.Cancel = true,窗口将关闭。
  • 但是我希望窗口取消关闭所以我需要设置 e.Cancel = true

标签: wpf events button


【解决方案1】:

我想我看不出这是什么意外行为。

如果您将其指定为Cancel 按钮并调用.ShowDialog(),则单击该按钮将关闭窗口。

您已将自己的调用添加到 Close() 并取消了关闭,因此两次调用都已进行,并且两次都引发了事件。

更新

在回答您关于它为何会以这种方式运行的评论时,IsCancelIsDefault 属性提供了一种简单的机制来仅使用 XAML 定义对话框。它们省去了您必须进入代码隐藏来定义样板点击处理程序的麻烦。

【讨论】:

  • 我认为如果行为正确,应该是对 exitButton_Click 的一次调用。 IsCancel = True 仅用于在用户按下 ESC 时激活 exitButton_Click。此外,仅当您从另一个窗口调用此窗口(包含此退出按钮)时才会发生这种情况。所以我认为这是一个错误。
  • 你是对的。当我使用 .ShowDialog() 时,如果我设置 IsCancel = True,将会调用更多一个额外的 close()。我不明白为什么 MS 会设计这样的东西。
猜你喜欢
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2013-01-01
  • 2013-03-28
  • 2013-09-12
  • 1970-01-01
相关资源
最近更新 更多