I use some UserControls
which get created and destroyed within my application during runtime (by creating and closing subwindows with these controls inside).
It
WPF doesn't support IDisposable
well. If you're implementing a WPF control that needs cleanup, you should think about hooking into the Loaded and Unloaded events instead (or in addition).
I.e. you connect to the event in the Loaded
handler and disconnect in the Unloaded
handler. Of course this is only an option if your control does not need to receive the event while it's not "loaded" and if you can correctly support many load/unload cycles.
The advantage of using the Loaded
/Unloaded
events is that you don't have to manually dispose the user control everywhere it's used. You should however be aware that the Unloaded
event is not fired after application shutdown has begun. E.g. if your shutdown mode is OnMainWindowClose
, the Unloaded
events for other windows will not be fired. This usually isn't a problem though. It just means that you cannot do stuff reliably in an Unloaded
that must happen before/while the application terminates.