TalkingCode
TalkingCode

Reputation: 13557

What happens to a WPF window after it is closed?

in my WPF application I sometimes need to create a small helper window and I create the instance of the window the first time I need it.

if (mesareaderThreadQueWin == null)
{
    mesareaderThreadQueWin = new MesaReaderThreadQueWindow();    
}

mesareaderThreadQueWin.Show(); 

This works perfect so far. But if I close the window and invoke to code again the program crashes telling me I can't do show after the window already did close.

I wonder a little bit what exactly is happening here. The window is not null otherwise the code would just create a new instance but since I already have shown the window it seems like i can't do so again. So the window must be in some kind of in-between-state. Unable to become visible but not null.

Can I detect this state? Its there a way to reuse this window again other then not closing the window at all and using hide instead?

Upvotes: 6

Views: 2310

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178690

You could handle the Closing event, cancel it, then hide the window:

window.Closing += delegate(object sender, CancelEventArgs e)
{
    e.Cancel = true;
    window.Hide();
};

This ensures the Window never closes and allows you to call Show() any number of times.

It's probably superfluous given the above, but you could detect when your Window is closed by attaching to the Closed event and setting a flag there. That is, maintain your own isClosed variable.

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292465

Can I detect this state?

As far as I know, there is no way to access this state

Its there a way to reuse this window again other then not closing the window at all and using hide instead?

Yes, handle the Closing event in the dialog window, or override the OnClosing method:

protected override void OnClosing(CancelEventArgs e)
{
    e.Cancel = true;
    this.Hide();
}

Upvotes: 4

Related Questions