无法在 WPF 中设置 DialogResult [英] Can't set DialogResult in WPF

查看:44
本文介绍了无法在 WPF 中设置 DialogResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调用窗口中使用 ShowDialog() 显示 WPF 窗口.窗口打开并且是模态的,如预期的那样.但是,在对话框窗口中的确定"和取消"按钮的单击事件中,我分别设置了 this.DialogResult = true (或 false),并且没有设置该值.窗口按预期关闭,但 DialogResult 仍然为空.

I show a WPF window using ShowDialog() from the calling window. The window opens and is modal as expected. However, in my OK and Cancel button's click events in the dialog window I set this.DialogResult = true (or false) respectively, and the value does not get set. The window closes as expected, but DialogResult is still null.

这是 WPF 中的错误吗?或者是否有原因无法设置 DialogResult 属性但不会引发异常?该窗口未托管在浏览器中.

Is this a bug in WPF? Or is there a reason the DialogResult property cannot be set yet does not throw an exception? The window is not hosted in a browser.

调用窗口中的代码:

Window2 win = new Window2();
bool? result = win.ShowDialog();
if (result.HasValue && result.Value) {
   //never gets here because result is always null
}

对话窗口中的代码:

this.DialogResult = true;

推荐答案

DialogResult 是一个可为空的 bool.但是,您不必强制转换它来获得它的价值.

DialogResult is a nullable bool. However you do not have to cast it to get it's value.

bool? result = myWindow.ShowDialog();
if (result ?? false)
{
  // snip
}

??如果结果为空,则设置要返回的默认值.更多信息:使用可空类型(C# 编程指南)

The ?? sets the default value to return if the result is null. More information: Using Nullable Types (C# Programming Guide)

至于最初的问题,我唯一一次看到并追踪到这个问题是在设置 DialogResult 和关闭窗口之间设置窗口时.不幸的是,我能提供的唯一建议是让您逐步检查代码并检查操作的顺序.我相信我通过设置 DialogResult 然后显式关闭窗口来修复"它.

As for the original question, the only time I have seen and traced this issue is when the window was being disposed between setting the DialogResult and closing the window. Unfortunately the only advice that I can offer is for you step through your code and check the order of the operations. I believe that I "fixed" it by setting the DialogResult and then explicitly closing the window.

这篇关于无法在 WPF 中设置 DialogResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆