WPF:不能重复使用的窗口已经关闭后,重复使用、窗口、WPF

2023-09-02 01:48:26 作者:卑微的挽留

我想保持窗口身边的一个实例,并在需要时调用的ShowDialog 。这个工作找的WinForms,但在WPF我收到此异常:

  

System.InvalidOperationException:无法设置可见性或来电显示,ShowDialog的,或WindowInteropHelper.EnsureHandle后,窗口已关闭

有没有办法做这样的事情在WPF?

  MyWindow.Instance.ShowDialog();

公共类mywindow的:窗口
{
    私有静态mywindow的_instance;

    公共静态mywindow的实例
    {
        如果(_instance == NULL)
        {
            _instance =新窗口();
        }
        返回_instance();
    }
}
 

解决方案

我想你的可以的做,如果你改变了窗口的可见性,而不是将其关闭。你需要做的,在闭幕()事件,然后取消关闭。如果允许关闭的情况发生,你肯定不能重新打开已关闭的窗口 - 从这里:

  

如果Closing事件不取消,   会发生以下情况:

     

...

     

在窗口中创建非托管资源配置。

WPF基础入门2 WPF窗口类和垂直布局面板基本使用

在出现这种情况的窗口,将永远不会再次有效。

我不认为这是值得的,虽然 - 它确实是没有那么多的性能损失,使每一次一个新的窗口,你不太可能硬介绍给调试错误/内存泄漏。 (另外你需要确保它没有关闭,释放它的资源,当应用程序被关闭)

刚刚看了您正在使用的ShowDialog(),这将使窗口模式,只是隐藏它不会控制权返回给父窗口。我怀疑这是可能做到这一点在所有与模态窗口。

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();
    }
}

解决方案

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.