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.
If I'm not wrong, you can cancel the closing event of that window and instead set visibility to hidden
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Visibility = Visibility.Hidden;
}
Try this:
protected override void OnClosing(CancelEventArgs e)
{
this.Visibility = Visibility.Hidden;
e.Cancel = true;
}
When we try to show the Window which is closed, we will get the following exception.
"Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed."
So to handle this case it would be better if we use Visibility option of the window. We need to set the visibility of the window to Hidden or Collapsed instead of closing it directly.
this.Visibility = System.Windows.Visibility.Collapsed or Hidden;
If we want to show it again, just set the visibility to Visible
this.Visibility = System.Windows.Visibility.Visible;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With