我有一个表单,上面有一个面板,我会在这个面板上动态加载多个用户控件。我为每个控件处理事件。
UserControl userControl1 = LoadControl("control.ascx") as UserControl;
userControl1.Event += new ControlEventHandler(userControl_Event);
this.Panel.Controls.Add(userControl1);
UserControl userControl2 = LoadControl("control.ascx") as UserControl;
userControl2.Event += new ControlEventHandler(userControl_Event);
this.Panel.Controls.Add(userControl2);
...
现在当我删除面板上的控件时,我只需要执行以下操作:
this.Panel.Controls.Clear();
Clear()函数是否负责清除事件,还是我需要自己处理?
foreach(Control control in this.Panel.Controls)
{
UserControl userControl = control as UserControl;
if(userControl != null)
{
userControl -= userControl_Event;
}
}
在清除Panel的内容之前,有什么需要注意的吗?
基本上,我正在寻找一种动态加载用户控件并处理其事件的方法,而不会在摆脱它们时创建泄漏。
谢谢!
编辑: 因为我的控件是在页面的Page_Init事件中动态创建的(每次都是如此),所以它们的生命周期不能比页面的生命周期更长,这样说是正确的吗? 据我所知,控件在回发后不存在。每次都会创建一个新的控件。因此,我不必注销事件,因为对象在下一个页面加载时甚至不存在。这是正确的吗?