简体   繁体   中英

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

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

The code is taken from a book (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:

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

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

You are trying to open your window 2 times with every call to 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 DialogResult is Nullable. If there is a chance that you are closing the window without setting the DialogResult, check for null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM