开发者

Subscribing to an event defined in the base user control - ASP.NET

开发者 https://www.devze.com 2023-02-22 11:58 出处:网络
I have a base user co开发者_运维技巧ntrol (inherited from System.Web.UI.UserControl) public delegate void MyEventHandler(object sender, MyEventArgs e);

I have a base user co开发者_运维技巧ntrol (inherited from System.Web.UI.UserControl)

public delegate void MyEventHandler(object sender, MyEventArgs e);
public event MyEventHandler ControlLoaded;

//Fire the event from here
protected override void OnLoad(EventArgs e)
{
  MyEventArgs cmdEventArgs = new MyEventArgs("somearg");
  ControlLoaded(this, cmdEventArgs);
}

I have several controls that are derived from this base user control.

On the host ASPX page, I need to subscribe to the ControlLoaded event.

protected void Page_Load(object sender, EventArgs e)
{
  //subscribe to the event
  //This line DOES NOT WORK as I cannot attach event to a base control - It needs an instance of the user control which I don't have
  BaseUserControl.ControlLoaded += new MyEventHandler(ControlLoaded);
}

private void ControlLoaded(object sender, MyEventArgs e)
{
 // some control has been loaded
}

How do I subscribe to the ControlLoaded event? Thanks


You can't really subscribe to an instance event without having an instance to subscribe to. You could do this using a static event on BaseUserControl. This, however, is not a good idea; since you would need to be absolutely sure to unsubscribe from that event before the request finishes, in order to prevent a memory leak.

0

精彩评论

暂无评论...
验证码 换一张
取 消