【发布时间】:2017-12-31 18:41:33
【问题描述】:
我有一个从父表单启动的子表单:
ConfigForm cfg = new ConfigForm();
cfg.ShowDialog();
此子表单用于配置一些应用程序参数。 我想检查是否有一些更改未保存,如果有,警告用户。 所以我的 On OnClosing 事件是这样声明的:
private async void ChildFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Here i call a function that compare the current config with the saved config
bool isUptated = CheckUnsavedChanges();
// If updated is false, it means that there are unsaved changes...
if (!isUpdated)
{
e.Cancel = true;
// At this point i create a MessageDialog (Mahapps) to warn the user about unsaved changes...
MessageDialogStyle style = MessageDialogStyle.AffirmativeAndNegative;
var metroDialogSettings = new MetroDialogSettings()
{
AffirmativeButtonText = "Close",
NegativeButtonText = "Cancel"
};
var result = await this.ShowMessageAsync("Config", "There are unsaved changes, do you want to exit?", style, metroDialogSettings);
// If we press Close, we want to close child form and go back to parent...
if (result == MessageDialogResult.Affirmative)
{
e.Cancel = false;
}
}
}
我的逻辑是,如果我将 e.cancel 声明为 false,它将继续关闭表单,但它没有发生,子表单保持打开状态。
我的猜测是异步调用正在做一些我不明白的事情,因为如果我以这种方式声明 ChildFormClosing:
private async void ChildFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
bool isUptated = CheckUnsavedChanges();
e.Cancel = true;
if (!isUpdated)
{
MessageDialogStyle style = MessageDialogStyle.AffirmativeAndNegative;
var metroDialogSettings = new MetroDialogSettings()
{
AffirmativeButtonText = "Close",
NegativeButtonText = "Cancel"
};
var result = await this.ShowMessageAsync("Config", "There are unsaved changes, do you want to exit?", style, metroDialogSettings);
if (result == MessageDialogResult.Affirmative)
{
e.Cancel = false;
}
}
else
{
e.Cancel = false;
}
}
最后的 else e.Cancel = false 有效并且子窗体被关闭...
有什么线索吗? 谢谢!
【问题讨论】:
-
为什么需要异步显示消息?既然您在窗口的事件处理程序中,那不应该已经在 UI 线程上吗?
-
@Andy 你是对的......如果我将 ShowMessageAsync 更改为 ShowModalMessageExternal (不是异步方法),问题就解决了。尽管这并不能解释这种奇怪的行为(我想知道到底发生了什么,你知道......)如果你发表你的评论作为答案,我会非常乐意将其标记为好的。谢谢!
标签: wpf async-await formclosing