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

Jat*_*ing 6 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(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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Ps:抱歉,我忘了说只有从父窗口调用窗口时才会出现此错误.

Jay*_*Jay 7

我想我不知道这是出乎意料的行为.

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

您已添加自己的呼叫Close()并取消了关闭,因此两次呼叫都会发出,并且事件都会被提升两次.

更新

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