Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tell if a WPF Window is closed?

Tags:

wpf

I'm working on an application that displays some child windows which can either be closed by the user or are automatically closed. While debugging some exceptions that were being thrown, I discovered I was trying to call methods like Hide() on a window that had already been closed; this particular branch of code was common to both cases and I hadn't noticed this.

One of my first ideas was to look for a property on Window that would indicate the window had been closed. I can't seem to find one. In WinForms, I'd look to the IsDisposed property for a somewhat reliable indicator that the form had been closed (it won't reliably work for a dialog but I'm not working with dialogs.) I don't see anything equivalent on Window. The documentation for Window.Close() doesn't seem to indicate any properties that are changed by the method. Am I missing something obvious, or is the only method to know if a window's been closed to handle the Closed event? That seems kind of a harsh requirement for a simple task.

like image 666
OwenP Avatar asked Dec 19 '08 19:12

OwenP


People also ask

How do I know if a WPF window is open?

In WPF there is a collection of the open Windows in the Application class, you could make a helper method to check if the window is open. Here is an example that will check if any Window of a certain Type or if a Window with a certain name is open, or both. Show activity on this post. Show activity on this post.

How do I close a WPF window?

Pressing ALT + F4 . Pressing the Close button. Pressing ESC when a button has the IsCancel property set to true on a modal window.

What is window closing?

The Window. close() method closes the current window, or the window on which it was called. This method can only be called on windows that were opened by a script using the Window. open() method.


2 Answers

According to this conversation on the MSDN WPF forums (see the last post), you can check to see if the IsLoaded is false, which means that the window is "eligible" for unloading its content. I hope that works for you!

like image 144
scwagner Avatar answered Oct 01 '22 01:10

scwagner


If you derive from the Window class, you can do this:

public bool IsClosed { get; private set; }

protected override void OnClosed(EventArgs e)
{
    base.OnClosed(e);
    IsClosed = true;
}

It has an advantage over registering for the Closed event - no need to un-register the callback.

like image 22
Tom Avatar answered Oct 01 '22 00:10

Tom