WPF 窗口 ShowDialog() 导致无法设置可见性或调用 Show

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19070991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:45:07  来源:igfitidea点击:

WPF Window ShowDialog() causing Cannot set Visibility or call Show

c#wpfwpf-controls

提问by Jim

I am creating a wpf form which is going to be used for adding/editing data from datagrid. However when I check for ShowDialog() == trueI am getting the above exception.

我正在创建一个 wpf 表单,它将用于从 datagrid 添加/编辑数据。但是,当我检查ShowDialog() == true时,出现上述异常。

The code is taken from a book (Windows Presentation Foundation 4.5 Cookbook).

该代码取自一本书(Windows Presentation Foundation 4.5 Cookbook)。

UserWindow usrw = new UserWindow();
usrw.ShowDialog();
if (usrw.ShowDialog() == true)
{
     //do some stuff here;               
}

And on the WPF window:

在 WPF 窗口中:

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

How I can handle this?

我该如何处理?

===============================

================================

The solution to the problem was simply to remove usrw.ShowDialog(); and it start working as expected

解决问题的方法很简单,就是去掉 usrw.ShowDialog(); 它开始按预期工作

UserWindow usrw = new UserWindow();
//usrw.ShowDialog();
if (usrw.ShowDialog() == true)
{
     //do some stuff here;               
}

回答by Florian

You are trying to open your window 2 times with every call to ShowDialog()

每次调用时,您都试图打开窗口 2 次 ShowDialog()

try

尝试

UserWindow usrw = new UserWindow();
bool result =(bool)usrw.ShowDialog();
if (result)
{
     //do some stuff here;               
}

or

或者

UserWindow usrw = new UserWindow();
usrw.ShowDialog();
if ((bool)usrw.DialogResult)
{
    //do some stuff here;               
}

keep in mind that DialogResultis Nullable. If there is a chance that you are closing the window without setting the DialogResult, check for null.

请记住,它DialogResult是可空的。如果您有可能在没有设置 DialogResult 的情况下关闭窗口,请检查null.