无法在 WPF 中设置 DialogResult

发布于 2024-07-22 06:17:14 字数 531 浏览 12 评论 0原文

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

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

调用窗口中的代码:

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

对话窗口中的代码:

this.DialogResult = true;

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.

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.

Code in the calling window:

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

Code in the dialog window:

this.DialogResult = true;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

恍梦境° 2024-07-29 06:17:14

DialogResult 是一个可为 null 的布尔值。 但是,您不必强制转换它即可获得它的值。

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

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

至于原来的问题,我唯一一次看到并跟踪这个问题是在设置 DialogResult 和关闭窗口之间处理窗口时。 不幸的是,我可以提供的唯一建议是让您逐步执行代码并检查操作的顺序。 我相信我通过设置 DialogResult 然后显式关闭窗口来“修复”它。

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
}

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

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.

扮仙女 2024-07-29 06:17:14

首先,您必须考虑到它返回一个可为空的布尔值(布尔?),因此为了比较它或将其设置为另一个变量,您必须将其转换为常规布尔值

bool result = (bool)myWindow.DialogResult;

至于它是否为空......我不明白为什么会发生这种情况,除非它在设置为 true 或 false 后以某种方式设置回 null。 你能展示你的代码吗?

编辑:

你的代码对我来说工作得很好,这就是我在第二个窗口中的内容:

private void button2_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = false;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
}

在 Window1 中:

private void window1_Loaded(object sender, RoutedEventArgs e)
{
    Window2 win = new Window2();

    bool? result = win.ShowDialog();

    if (result.HasValue && result.Value)
    {
        //it DID get here
    }
}

有什么大的区别吗?

Well first of all you have to take into account that it returns a nullable bool (bool?), so in order to compare it or set it to another variable you have to cast it to a regular bool

bool result = (bool)myWindow.DialogResult;

As for it being null... I don't see why that should happen, unless it's somehow being set back to null AFTER being set to true or false. Can you show your code?

EDIT:

Your code worked fine for me, this is what I have in the second window:

private void button2_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = false;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
}

And in Window1:

private void window1_Loaded(object sender, RoutedEventArgs e)
{
    Window2 win = new Window2();

    bool? result = win.ShowDialog();

    if (result.HasValue && result.Value)
    {
        //it DID get here
    }
}

Is there any big difference?

等数载,海棠开 2024-07-29 06:17:14

我刚刚遇到了完全相同的问题,这似乎是由我重写 OnClosing() 方法引起的。 我需要重写 OnClosing() 以阻止用户通过关闭 (X) 按钮关闭模式窗口。

当我注释掉 OnClosing() 方法时,问题就消失了,并且 DialogResult 返回了预期的 true 或 false 值(按设置)。

有趣的是我的按钮单击处理程序和 OnClosing 方法:

private void AlternateButton_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = false;
    buttonHasBeenClicked = true;
    this.Close();
}

private void DefaultButton_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
    buttonHasBeenClicked = true;
    this.Close();
}

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    base.OnClosing(e);
    if (!buttonHasBeenClicked)
    {
        // Prevent the user closing the window without pressing one of the buttons.
        e.Cancel = true;
    }
}

I have just had exactly the same problem and it seems to be caused by my overriding the OnClosing() method. I needed to override OnClosing() to stop the user closing the modal window via the close (X) button.

When I comment out the OnClosing() method, the problem goes away and the DialogResult is returned with the expected values of true or false, as set.

For interest here was my button click handlers and OnClosing method:

private void AlternateButton_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = false;
    buttonHasBeenClicked = true;
    this.Close();
}

private void DefaultButton_Click(object sender, RoutedEventArgs e)
{
    this.DialogResult = true;
    buttonHasBeenClicked = true;
    this.Close();
}

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    base.OnClosing(e);
    if (!buttonHasBeenClicked)
    {
        // Prevent the user closing the window without pressing one of the buttons.
        e.Cancel = true;
    }
}
难理解 2024-07-29 06:17:14

我也遇到了这个问题,我发现解决这个问题的唯一方法是在我的类中使用这段代码:

public new bool? DialogResult { get; set; }

在设置我的 DialogResult 之后,它对我有用! (非常奇怪的问题)。
这是我正在使用的代码:

cmdCancel = new RelayCommand(() => { DataContact.Reload(); this.DialogResult = false; this.Close(); });

并打开我的对话框:

public static MessageBoxResult ShowQuestionYesNo(string message)
        {
            POLMessageBox w = new POLMessageBox("سوال", MessageBoxType.QuestionYesNo, message);
            w.ShowDialog();
            var b = w.DialogResult;
            if (b == true) return MessageBoxResult.Yes;
            if (b == false) return MessageBoxResult.No;
            return MessageBoxResult.No;
        }

I have been into this problem too, and the only way i have found to fix it was using this code in my Class :

public new bool? DialogResult { get; set; }

and after setting my DialogResult it work out for me !! ( very strange issue ).
this was the code i was using :

cmdCancel = new RelayCommand(() => { DataContact.Reload(); this.DialogResult = false; this.Close(); });

and to open my dialog :

public static MessageBoxResult ShowQuestionYesNo(string message)
        {
            POLMessageBox w = new POLMessageBox("سوال", MessageBoxType.QuestionYesNo, message);
            w.ShowDialog();
            var b = w.DialogResult;
            if (b == true) return MessageBoxResult.Yes;
            if (b == false) return MessageBoxResult.No;
            return MessageBoxResult.No;
        }
半﹌身腐败 2024-07-29 06:17:14

在设置 DialogResult 之前是否关闭窗口?
您应该发布按钮事件处理程序的全部内容。

Do you close the window before u set the DialogResult?
You should post the whole content of your button event-handlers.

-黛色若梦 2024-07-29 06:17:14

我刚刚也遇到了这个问题。 事实证明,我已将 DialogResult 设置在 IF 语句的大括号内,因此(尽管看起来很奇怪)导致了错误。 一旦删除这一行,问题就解决了。

private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(startBlockPosBox.Text))
        {
          .. do stuff ..
        }
        else
        {
          .. do stuff ..
          DialogResult = true; // this line caused the problem
        }

        DialogResult = true;
    }

I just ran into the problem too. It turns out I had set DialogResult inside a brace of an IF statement and for this reason (as odd as it may seem) caused the error. As soon as this single line was removed, the problem was resolved.

private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(startBlockPosBox.Text))
        {
          .. do stuff ..
        }
        else
        {
          .. do stuff ..
          DialogResult = true; // this line caused the problem
        }

        DialogResult = true;
    }
药祭#氼 2024-07-29 06:17:14

我在对话框窗口页面中有以下内容。 (dialogwindow.xaml.cs)

   private void dlgWindowYesButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
        this.Close();
    }

    private void dlgWindowNoButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = false;
        this.Close();
    }

在调用页面中我使用了如下的dialogwindow:

dialogwindow dWinObj = new dialogwindow();
if(dWinObj.ShowDialog().Value == true)
{
  //perform the operation when the user clicks "Yes"
}

I have the following in the dialog window page. (dialogwindow.xaml.cs)

   private void dlgWindowYesButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
        this.Close();
    }

    private void dlgWindowNoButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = false;
        this.Close();
    }

In the calling page I used the dialogwindow like this:

dialogwindow dWinObj = new dialogwindow();
if(dWinObj.ShowDialog().Value == true)
{
  //perform the operation when the user clicks "Yes"
}
过去的过去 2024-07-29 06:17:14

问题是由于表单的生命周期造成的:

对话框事件
私人无效_loginViewModel_LoginEvent(对象发送者,LoginViewModel.LoginEventArgs e)
{
对话框结果 = true;
this.Close();
}

有效:

var login = new Login();
var result = login.ShowDialog();

无效:

var result = new Login().ShowDialog();

The problem is due to the life of the form:

Dialog event
private void _loginViewModel_LoginEvent(object sender, LoginViewModel.LoginEventArgs e)
{
DialogResult = true;
this.Close();
}

Works:

var login = new Login();
var result = login.ShowDialog();

Does NOT work:

var result = new Login().ShowDialog();
素罗衫 2024-07-29 06:17:14

我通过添加 this.close() 解决了这个问题,然后添加 this.DialogResult=truewindow.ShowDialog() return 正确。

private void Button1_Click(object sender, RoutedEventArgs e)
{
    this.Close();
    this.DialogResult = true;
}

I fixed this problem with adding this.close() after that add this.DialogResult=true and window.ShowDialog() return true.

private void Button1_Click(object sender, RoutedEventArgs e)
{
    this.Close();
    this.DialogResult = true;
}
玩物 2024-07-29 06:17:14

我遇到了类似的问题,但我的问题来自结束语中的代码。 我试图在窗口关闭之前 Dispose() 一个列表,然后将 List<> 设置为 属性为 null...当我尝试将其值设置为 null 时,它被设置属性阻塞,因此我在设置属性方法中想出了以下笨拙的解决方法,然后一切正常:

    List<SettingItem> settingItems;
    public IEnumerable<SettingItem> Settings
    {
        get
        {
            return settingItems.OrderBy(t => t.Name).AsEnumerable();
        }
        set
        {
            if (value == null)
            {
                settingItems.Clear();
            }
            else
            {
                settingItems = value.ToList();
            }
        }
    }

I had a similar issue, but my issue came from the code within my closing statement. I was trying to Dispose() a List before the window closed, and then set the List<> property to null... it was choking on the set property when I was trying to set its value to null so I came up with the following clumsy workaround in my set property method and everything worked afterward:

    List<SettingItem> settingItems;
    public IEnumerable<SettingItem> Settings
    {
        get
        {
            return settingItems.OrderBy(t => t.Name).AsEnumerable();
        }
        set
        {
            if (value == null)
            {
                settingItems.Clear();
            }
            else
            {
                settingItems = value.ToList();
            }
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文