无法在WPF中设置DialogResult

无法在WPF中设置DialogResult

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

问题描述

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

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是可为null的布尔值.但是,您不必强制转换它即可获得其价值.

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
}

??设置默认值,如果结果为null则返回.更多信息:使用可空类型(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:17