无法在 WPF 中设置 DialogResult

Can#39;t set DialogResult in WPF(无法在 WPF 中设置 DialogResult)
本文介绍了无法在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)