views:

50

answers:

1

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();
    }
}
+4  A: 

I suppose you could do it if you changed visibility of the window rather than closing it. You'd need to do that in the Closing() event and then cancel the close. If you allow the close to happen you certainly can't reopen a closed window - from here:

If the Closing event isn't canceled, the following occurs:

...

Unmanaged resources created by the Window are disposed.

After that happens the window will never be valid again.

I don't think it's worth the effort though - it really isn't that much of a performance hit to make a new window each time and you are far less likely to introduce hard to debug bugs / memory leaks. (Plus you'd need to make sure that it did close and release it's resources when the application is shut down)


Just read that you are using ShowDialog(), this will make the window modal and simply hiding it won't return control to the parent window. I doubt it is possible to do this at all with modal windows.

Martin Harris