How to know when a UserControl is no longer used (no Close event)

五迷三道 提交于 2019-12-24 02:37:14

问题


I'm using UserControls inside a WinForm to 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.


回答1:


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.




回答2:


There is a HandleDestroyed event on the Control that might work for you.




回答3:


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.



来源:https://stackoverflow.com/questions/7256021/how-to-know-when-a-usercontrol-is-no-longer-used-no-close-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!