WPF: Cannot reuse window after it has been closed

Viewed 76366

I am trying to keep one instance of a Window around and when needed call ShowDialog. This worked find in winforms, but in WPF I recieve this exeception:

System.InvalidOperationException: Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.

Is there any way to do something like this in WPF?

MyWindow.Instance.ShowDialog();

public class MyWindow : Window
{
    private static MyWindow _instance;

    public static MyWindow Instance
    {
        if( _instance == null )
        {
            _instance = new Window();
        }
        return _instance();
    }
}
9 Answers

Try this:

protected override void OnClosing(CancelEventArgs e)
{
    this.Visibility = Visibility.Hidden;
    e.Cancel = true;
}

if you cancel the close event and set visibility =hidden then you can override this issue

Private Sub ChildWindow_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        e.Cancel = True
        Me.Visibility = Windows.Visibility.Hidden
End Sub

It's maybe a logic that i don't understand but closing a window it's not reversible

if you want to "close" your window and re opening hit with a button you can actualy Hide it like this:

 private MyWindow myWindow;
 private void OpenMyWindow_OnClick(object sender, RoutedEventArgs e)
 {
     if (myWindow == null)
     {
         myWindow = new MyWindow();
     }

     if(!myWindow.IsVisible)
     {
         myWindow.Show();
     }
     else
     {
         myWindow.Hide();
     }
 }

If your window can be closed i suggest you to handle it with the Closed event. (here's the solution i used)

private MyWindow myWindow;
private void OpenMyWindow_OnClick(object sender, RoutedEventArgs e)
{
    if (myWindow == null)
    {
        myWindow = new MyWindow();
        myWindow.Closed += OnMyWindowClosed;
    }

    if(!myWindow.IsVisible)
    {
        myWindow.Show();
    }
    else
    {
        myWindow.Hide();
    }
}

private void OnMyWindowClosed(object obj, EventArgs e)
{
    myWindow = null;
}

I hope I helped someone

Related