I'm using UserControl
s inside a WinForm
t开发者_StackOverflow中文版o display data.
I'm also using the command pattern so that the UserControl
registers a (weak) event and does stuff when the command is triggered.
On a WinForm
I can unregister the events in the Close
event. However there's no such event on a UserControl
.
I hooked up the events I thought would be fired when the UserControl
is no longer in the display stack but could find nothing useful.
To get by I check if the Parent
is null and that worked for most of the cases.
Now I'd like to have a child UserControl
of another UserControl
(put the UserControl
inside a TabControl
) and the Parent
property isn't going to be null for the child control anymore when the parent is no longer displayed.
Is there any way to know if the UserControl
is used?
What I've tried so far: Dispose()
doesn't get called straight away by the system so it's no useful; IsVisible
doesn't get updated by the system either; there is no Close
or Unload
event fired.
Cheers.
There is a HandleDestroyed event on the Control that might work for you.
It really is the Dispose() method. If it doesn't get called early enough then there's a bug in the code that uses the control. Using Controls.Clear() or Controls.Remove() for example.
The parent of a control always iterates its Controls collection and disposes the child controls when it gets disposed. Which makes disposing automatic, starting at the form's Dispose() which runs when the form is closed. It is however not automatic when you remove controls yourself.
In the past I dealt with this problem by getting the parent form (using Control.ParentForm) and then hooking up to the FormClosing event directly.
The tricky part is knowing when to call ParentForm. It's not set when the user control is first created. Sometimes I override the OnLayout handler and monitor until the ParentForm is not null.
精彩评论