我意识到当我使用属性 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:对不起,我忘了说这个错误只发生在你从父窗口调用你的窗口时。
最佳答案
我想我看不出这是出乎意料的行为。
如果您将其指定为 Cancel
按钮并调用.ShowDialog()
,然后单击该按钮将关闭窗口。
您已将自己的调用添加到 Close()
并取消了关闭,因此两次都进行了调用并且两次都引发了事件。
更新
为了回答您关于为什么它可能会以这种方式运行的评论,IsCancel
和 IsDefault
属性提供了一种简单的机制来仅使用 XAML 定义对话框。它们为您省去了必须进入代码隐藏来定义样板点击处理程序的麻烦。
关于wpf - 设置 exitButton.IsCancel = True 时触发两次关闭事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351543/