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

时间:2011-12-02 03:47:26

标签: wpf events button

我意识到当我设置具有属性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:抱歉,我忘了说只有当您从父窗口调用窗口时才会出现此错误。

1 个答案:

答案 0 :(得分:5)

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

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

您已将自己的电话添加到Close()并取消了关闭,因此两次调用均已完成并且事件都会被提升。

更新

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