Wpf 设置exitButton.IsCancel=True时触发两次关闭事件

Wpf 设置exitButton.IsCancel=True时触发两次关闭事件,wpf,events,button,Wpf,Events,Button,我意识到当我设置属性为IsCancel=True的退出按钮时,窗口的关闭事件将触发两次 private void exitButton_Click(object sender, RoutedEventArgs e) { // this button was set attribute IsCancel = True. Close(); } private void BaseWindow_Closing(obje

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

    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:对不起,我忘了说这个错误只有在您从父窗口调用窗口时才会发生。

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

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

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

更新
在回答您关于为什么它会这样做的评论时,
IsCancel
IsDefault
属性提供了一种仅使用XAML定义对话框的简单机制。它们为您省去了必须进入codebehind来定义样板点击处理程序的麻烦。

如果删除
e.Cancel=true
窗口实际关闭,会发生什么情况?是,如果我删除e.Cancel=true,窗口将关闭。但我希望窗口取消关闭,因此我需要设置e.Cancel=true。我认为如果它运行正常,应该调用一次exitButton\u Click。IsCancel=True,仅用于在用户按ESC键时激活exitButton\u单击。此外,只有从另一个窗口调用此窗口(包含此退出按钮)时,才会发生这种情况。所以我认为这是一个错误,你是对的。当我使用.ShowDialog()时,如果我设置IsCancel=True,则会调用多个额外的close()。我不明白为什么微软会设计这样的东西。