WPF ShowDialog again/several times

0

i´ve got an WPF application with an "settings-winwow". if i´m clicking on "info" on the mainwindow, settings.showDialog(); is called - so far so good. It opens and i can do some stuff, bus when i´m closing it and try to open it again, it gives me an error. its called:

System.InvalidOperationException

HResult=0x80131509

message = Visibility cant be shown or defined, ShowDialog or WindowInteropHelper.EnsureHandle cant be called, after the window was closed.

i found this:

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        e.Cancel = true;
        this.Visibility = Visibility.Hidden;
    }

here on SO, but i doesn´t work or maybe i´m using it the wrong way.. Can anybody help me?

wpf
asked on Stack Overflow Dec 4, 2018 by S Kirchner • edited Dec 5, 2018 by Lennart

3 Answers

1

You can only call ShowDialog once on the window. For the next call you need to create a new window.

So the code when clicking on the 'info ' should be:

settings = new SettingsWindow();
settings.ShowDialog();
answered on Stack Overflow Dec 4, 2018 by Matt Norrie
0

If you want to reuse the window you should consider to use Show instead of ShowDialog. ShowDialog will destroy the object when you close the window. Using `Show' won't block the calling main window. This may be undesirable in your case.

The codes snipped you posted will prevent the destruction of your object by hiding the window instead of closing it. If you want to use you snipped, the copy it to your window.

Your XAML code:

Window x:Class="WpfTestApp.DialogWindow"
    ...
    Closing="Window_Closing">

The C# code in code behind:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;
    this.Visibility = Visibility.Hidden;
}

or use Show instead like this:

DialogWindow.Show();
answered on Stack Overflow Dec 4, 2018 by fussel
0

You can call several times Window.ShowDialog()

But you should never call Close() method (until you don't want to use the control anymore: Close is like Dispose for controls).

Instead you can use Hide().

Then the next call to ShowDialog() should work as a Show() call.

When the dialog is hidden, other windows and other dialogs should continue to work as usual.

Transform Close() calls to Hide()

protected override void OnClosing(CancelEventArgs e)
{
    e.Cancel = true;
    Hide();
}
answered on Stack Overflow Nov 26, 2019 by Fab • edited Nov 26, 2019 by Fab

User contributions licensed under CC BY-SA 3.0