tags:

views:

972

answers:

3

I have a simple WPF single window application contains Textboxes and Buttons. And I also use NotifyIcon and DateTimePicker of Windows Forms in WPF window. How can I effectively dispose all the controls?

A: 

I would say that the same rule applies in WPF applications as in any other .NET applications: if an object implements IDisposable, you should call Dispose when you are done using it. If you dynamically load and unload controls, and they do not implement IDisposable, just setting any references to null (and detaching any event handlers) should be enough for the garbage collector to do its job.

Fredrik Mörk
A: 

If that control is a part of some IContainer (that's the common model in .NET) than your controls just needs implementation of IDisposable. Thus Dispose() will be called automatically when it is appropriate time.

terR0Q
+3  A: 

Hardly anything in WPF has a Dispose method. The vast majority of classes encapsulate purely managed information. You can attach an object into the tree (e.g. via a Children.Add method) and you can remove it again - that's how the state management works. It exactly doesn't fit into the IDisposable pattern, because once you've removed a control you can add it again, whereas Dispose means forever (although you could use Dispose to manage it in addition to Add/Remove methods).

A discussion about it on the Microsoft forums.

There are a few things that ought to be IDisposable but aren't, like DispatcherTimer, and there's nothing to stop you from implementing IDisposable on your own classes. It's up to you when to call Dispose; basically when you know you aren't going to be using the object any more.

For a Window you just call Close to close it, and WPF takes care of everything else.

Daniel Earwicker