Bubbling Events to Parent in ASP.NET

允我心安 提交于 2019-12-05 22:51:26

问题


I have say this hierarchy in ASP.NET:

page
  user control 1
     user control 2
         control 3

What I want to be able to do is that when control 3 (it could be any kind of control, I want to do this generically) has the user do something with it that triggers a postback, it bubbles up some event to user control 2, or maybe even user control 1 (though I could have UC 2 manually bubble the event too).

Again, I want to do this generically, so that the hierarchy can change and it still works. Maybe there are multiple controls (control 4, etc.) or a data bound control. Is this possible?

Thanks.


回答1:


Event Bubbling is built into asp.net

Check this out: http://www.4guysfromrolla.com/articles/051105-1.aspx

Basically, to raise the event that you want bubbled up:

RaiseBubbleEvent(this, args);

And then to catch it:

protected override bool OnBubbleEvent(object source, EventArgs e) {
    bool handled = false;

    if (e is TemplatedListCommandEventArgs) {
        TemplatedListCommandEventArgs ce = (TemplatedListCommandEventArgs)e;

        OnItemCommand(ce);
        handled = true;
    }
    return handled;
}

As the code implies, if this method returns false, the event will continue to bubble up the control hierarchy

The implementation of RaiseBubbleEvent is provided by Control and cannot be overridden. RaiseBubbleEvent sends the event data up the hierarchy to the control's parent. To handle or to raise the bubbled event, a control must override the OnBubbleEvent method.

From MSDN: http://msdn.microsoft.com/en-us/library/aa719644(v=vs.71).aspx



来源:https://stackoverflow.com/questions/5423713/bubbling-events-to-parent-in-asp-net

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