What is the correct way to dispose of a WPF window? What is the correct way to dispose of a WPF window? wpf wpf

What is the correct way to dispose of a WPF window?


Close() releases all unmanaged resources, and closes all owned Windows.

Any other managed resources you need deterministic disposal of should be handled from the Closed event.

Reference

(note: deleted previous answer, it was a completely wrong guess)


There are very few WPF elements that actually need to be explicitly disposed, unlike in Windows Forms.

In the case of Window, calling Close() is sufficient to dispose all managed and unmanaged resources accorrding to the documentation.


Just in case, I'll add my two cents.

My problem was that I didn't do enough troubleshooting. My window was a child window that could be opened, closed, and re-opened, so I added the following to keep it from closing completely:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {  e.Cancel = true;  this.Hide();}

However, when Window.Close was called, it only hid the window. I eventually caught on and added the following:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {  e.Cancel = true;  this.Hide();}public void Close() {  this.Closing -= Window_Closing;  //Add closing logic here.  base.Close();}

This works fine - it removes the event handler preventing the window from being closed, and then closes it.