Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

c# - WPF: Cannot reuse window after it has been closed

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...