事件冒泡控制項樣本

來源:互聯網
上載者:User
.NET Framework 開發員指南  
事件冒泡

ASP.NET 頁架構提供一種稱為“事件冒泡”的技術,允許子控制項將事件沿其包容階層向上傳播。事件冒泡允許在控制項階層中更方便的位置引發事件,並且允許將事件處理常式附加到原始控制項以及公開冒泡的事件的控制項上。

資料繫結控制項(Repeater、DataList 和 DataGrid)使用事件冒泡將子控制項(在項目模板內)引發的命令事件公開為頂級事件。雖然 .NET Framework 中的 ASP.NET 伺服器控制項將事件冒泡用於命令事件(事件數目據類是從 CommandEventArgs 派生的事件),但是,伺服器控制項上定義的任何事件都可以冒泡。

控制項可以通過從基類 System.Web.UI.Control 繼承的兩個方法參與事件冒泡。這兩個方法是:OnBubbleEventRaiseBubbleEvent。以下程式碼片段顯示了這些方法的簽名。

[C#]protected virtual bool OnBubbleEvent(   object source,   EventArgs args);protected void RaiseBubbleEvent(   object source,   EventArgs args );[Visual Basic]Overridable Protected Function OnBubbleEvent( _   ByVal source As Object, _   ByVal args As EventArgs _) As BooleanProtected Sub RaiseBubbleEvent( _   ByVal source As Object, _   ByVal args As EventArgs _)

RaiseBubbleEvent 的實現是由 Control 提供的,並且不能被重寫。RaiseBubbleEvent 沿階層向上將事件數目據發送到控制項的父級。若要處理或引發冒泡的事件,控制項必須重寫 OnBubbleEvent 方法。

使事件冒泡的控制項執行以下三種操作之一。

  • 控制項不執行任何操作,此時事件自動向上冒泡到其父級。
  • 控制項進行一些處理並繼續使事件冒泡。若要實現這一點,控制項必須重寫 OnBubbleEvent,並從 OnBubbleEvent 調用 RaiseBubbleEvent。以下程式碼片段(摘自模板化資料繫結控制項樣本)在檢查事件參數的類型後使事件冒泡。
    [C#]protected override bool OnBubbleEvent(object source, EventArgs e) {            if (e is CommandEventArgs) {                // Adds information about an Item to the                  // CommandEvent.                TemplatedListCommandEventArgs args =                    new TemplatedListCommandEventArgs(this, source, (CommandEventArgs)e);                RaiseBubbleEvent(this, args);                return true;            }            return false;        }[Visual Basic]Protected Overrides Function OnBubbleEvent(source As Object, e As EventArgs) As Boolean   If TypeOf e Is CommandEventArgs Then      ' Adds information about an Item to the        ' CommandEvent.      Dim args As New TemplatedListCommandEventArgs(Me, source, CType(e, CommandEventArgs))      RaiseBubbleEvent(Me, args)      Return True   End If   Return FalseEnd Function
  • 控制項停止事件冒泡並引發和/或處理該事件。引發事件需要調用將事件調度給接聽程式的方法。若要引發冒泡的事件,控制項必須重寫 OnBubbleEvent 以調用引發此冒泡的事件的 OnEventName 方法。引發冒泡的事件的控制項通常將冒泡的事件公開為頂級事件。以下程式碼片段(摘自模板化資料繫結控制項樣本)引發一個冒泡的事件。
    [C#]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;}[Visual Basic]Protected Overrides Function OnBubbleEvent(source As Object, e As EventArgs) As Boolean   Dim handled As Boolean = False      If TypeOf e Is TemplatedListCommandEventArgs Then      Dim ce As TemplatedListCommandEventArgs = CType(e, TemplatedListCommandEventArgs)            OnItemCommand(ce)      handled = True   End If   Return handledEnd Function

有關說明事件冒泡的樣本,請參見事件冒泡控制項樣本和模板化資料繫結控制項樣本。

注意   雖然啟用事件冒泡的方法 OnBubbleEvent 符合用於引發事件的方法的標準 .NET Framework 命名模式,但是沒有名為 BubbleEvent 的事件。在停止事件冒泡的控制項中,將冒泡事件公開為頂級事件。例如,DataList 控制項將其模板中控制項的 Command 事件公開為 ItemCommand 事件。另請注意,在 .NET Framework 中 OnEventName 方法的標準簽名有一個參數 (protected void OnEventName (EventArgs e))。但是,OnBubbleEvent 有兩個參數,這是因為該事件起源於控制項之外;第二個參數提供源。

到目前為止,本討論說明了控制項如何響應冒泡的事件。下面一節顯示如何創作一個定義冒泡的事件的控制項。

定義冒泡的事件

如果希望控制項為它所定義的事件啟用事件冒泡,則控制項必須從引發該事件的 OnEventName 方法調用 RaiseBubbleEvent。不需要在該控制項中做額外的工作。以下程式碼片段顯示了一個控制項,該控制項定義了一個啟用冒泡的 Command 事件。

[C#]protected virtual void OnCommand(CommandEventArgs e) {            CommandEventHandler handler = (CommandEventHandler)Events[EventCommand];            if (handler != null)                handler(this,e);            // The Command event is bubbled up the control hierarchy.            RaiseBubbleEvent(this, e);        } [Visual Basic]Protected Overridable Sub OnCommand(e As CommandEventArgs)   Dim handler As CommandEventHandler = CType(Events(EventCommand), CommandEventHandler)   If Not (handler Is Nothing) Then      handler(Me, e)   End If    ' The Command event is bubbled up the control hierarchy.   RaiseBubbleEvent(Me, e)End Sub

注意   事件冒泡並不限於命令事件。可以使用此處描述的機制使任何事件冒泡。

請參見

事件冒泡控制項樣本 | 模板化資料繫結控制項樣本

事件冒泡控制項樣本

下面的自訂控制項 EventBubbler 說明了一種簡單的事件冒泡情況。EventBubbler 是一個包含文字框 (TextBox)、按鈕 (Button) 和標籤 (Label) 控制項的複合控制項。EventBubbler 將命令事件從按鈕冒泡到父容器控制項(自身),並將它們公開為頂級事件。若要產生該樣本,請參見伺服器控制項樣本中的說明。

有關更切合實際的樣本,請參見模板化資料繫結控制項樣本。

[C#]using System;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace CustomControls {      public class EventBubbler : Control, INamingContainer    {      private int number = 100;      private Label label;      private TextBox box1;      private TextBox box2;            public event EventHandler Click;      public event EventHandler Reset;      public event EventHandler Submit;            public string Label      {         get         {            EnsureChildControls();            return label.Text;         }         set         {            EnsureChildControls();            label.Text = value;         }      }            public int Number      {         get         {            return number;         }         set         {            number = value;         }      }            public string Text1      {         get         {            EnsureChildControls();            return box1.Text;         }         set         {            EnsureChildControls();            box1.Text = value;         }      }            public string Text2      {         get         {            EnsureChildControls();            return box2.Text;         }         set         {            EnsureChildControls();            box2.Text = value;         }      }                  protected override void CreateChildControls()       {                  Controls.Add(new LiteralControl("<h3>Enter a number : "));                  box1 = new TextBox();         box1.Text = "0";         Controls.Add(box1);                  Controls.Add(new LiteralControl("</h3>"));                  Controls.Add(new LiteralControl("<h3>Enter another number : "));                  box2 = new TextBox();         box2.Text = "0";         Controls.Add(box2);                  Controls.Add(new LiteralControl("</h3>"));                  Button button1 = new Button();         button1.Text = "Click";         button1.CommandName = "Click";         Controls.Add(button1);                  Button button2 = new Button();         button2.Text = "Reset";         button2.CommandName = "Reset";         Controls.Add(button2);                  Button button3 = new Button();         button3.Text = "Submit";         button3.CommandName = "Submit";         Controls.Add(button3);                  Controls.Add(new LiteralControl("<br><br>"));         label = new Label();         label.Height = 50;         label.Width = 500;         label.Text = "Click a button.";         Controls.Add(label);               }            protected override bool OnBubbleEvent(object source, EventArgs e)       {            bool handled = false;         if (e is CommandEventArgs)         {            CommandEventArgs ce = (CommandEventArgs)e;            if (ce.CommandName == "Click")            {               OnClick(ce);               handled = true;               }              else if (ce.CommandName == "Reset")            {               OnReset(ce);               handled = true;               }            else if (ce.CommandName == "Submit")            {               OnSubmit(ce);               handled = true;               }                     }         return handled;                  }            protected virtual void OnClick (EventArgs e)      {         if (Click != null)         {            Click(this,e);         }      }            protected virtual void OnReset (EventArgs e)      {         if (Reset != null)         {            Reset(this,e);         }      }            protected virtual void OnSubmit (EventArgs e)      {         if (Submit != null)         {            Submit(this,e);         }      }     }}[Visual Basic]Option ExplicitOption StrictImports SystemImports System.WebImports System.Web.UIImports System.Web.UI.WebControlsNamespace CustomControls   Public Class EventBubbler      Inherits Control      Implements INamingContainer      Private _number As Integer = 100      Private _label As Label      Private _box1 As TextBox      Private _box2 As TextBox            Public Event Click As EventHandler      Public Event Reset As EventHandler      Public Event Submit As EventHandler            Public Property Label() As String         Get            EnsureChildControls()            Return _label.Text         End Get         Set            EnsureChildControls()            _label.Text = value         End Set      End Property            Public Property Number() As Integer         Get            Return _number         End Get         Set            _number = value         End Set      End Property            Public Property Text1() As String         Get            EnsureChildControls()            Return _box1.Text         End Get         Set            EnsureChildControls()            _box1.Text = value         End Set      End Property            Public Property Text2() As String         Get            EnsureChildControls()            Return _box2.Text         End Get         Set            EnsureChildControls()            _box2.Text = value         End Set      End Property            Protected Overrides Sub CreateChildControls()                  Controls.Add(New LiteralControl("<h3>Enter a number : "))                  _box1 = New TextBox()         _box1.Text = "0"         Controls.Add(_box1)                  Controls.Add(New LiteralControl("</h3>"))                  Controls.Add(New LiteralControl("<h3>Enter another number : "))                  _box2 = New TextBox()         _box2.Text = "0"         Controls.Add(_box2)                  Controls.Add(New LiteralControl("</h3>"))                  Dim button1 As New Button()         button1.Text = "Click"         button1.CommandName = "Click"         Controls.Add(button1)                  Dim button2 As New Button()         button2.Text = "Reset"         button2.CommandName = "Reset"         Controls.Add(button2)                  Dim button3 As New Button()         button3.Text = "Submit"         button3.CommandName = "Submit"         Controls.Add(button3)                  Controls.Add(New LiteralControl("<br><br>"))         _label = New Label()         _label.Height = Unit.Pixel(50)         _label.Width = Unit.Pixel(500)         _label.Text = "Click a button."         Controls.Add(_label)      End Sub             Protected Overrides Function OnBubbleEvent(source As Object, e As EventArgs) As Boolean         Dim handled As Boolean = False         If TypeOf e Is CommandEventArgs Then            Dim ce As CommandEventArgs = CType(e, CommandEventArgs)            If ce.CommandName = "Click" Then               OnClick(ce)               handled = True            Else               If ce.CommandName = "Reset" Then                  OnReset(ce)                  handled = True               Else                  If ce.CommandName = "Submit" Then                     OnSubmit(ce)                     handled = True                  End If               End If             End If         End If         Return handled      End Function            Protected Overridable Sub OnClick(e As EventArgs)         RaiseEvent Click(Me, e)      End Sub            Protected Overridable Sub OnReset(e As EventArgs)         RaiseEvent Reset(Me, e)      End Sub            Protected Overridable Sub OnSubmit(e As EventArgs)         RaiseEvent Submit(Me, e)      End Sub   End ClassEnd Namespace
在頁上使用事件冒泡控制項

下面的 ASP.NET 頁使用自訂事件冒泡控制項 EventBubbler,並將事件處理常式附加到其頂級事件。

[C#]<%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %><html><script language="C#" runat=server>        private void ClickHandler(Object sender,EventArgs e)        {           MyControl.Label = "You clicked the <b> Click </b> button";   }        private void ResetHandler(Object sender,EventArgs e)        {          MyControl.Text1 = "0";          MyControl.Text2 = "0";          }        private void SubmitHandler(Object sender,EventArgs e)        {          if ( Int32.Parse(MyControl.Text1) + Int32.Parse(MyControl.Text2) == MyControl.Number)           MyControl.Label = "<h2> You won a million dollars!!!! </h2>";          else            MyControl.Label = "Sorry, try again. The numbers you entered don't add up to" +            " the hidden number.";   }        </script>      <body><h1> The Mystery Sum Game </h1><br>         <form runat=server>              <Custom:EventBubbler id = "MyControl" OnClick = "ClickHandler" OnReset = "ResetHandler" OnSubmit = "SubmitHandler" Number= "10" runat = server/>                                     </form>                       </body>                    </html>                  [Visual Basic]<%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %><html><script language="VB" runat=server>    Private Sub ClickHandler(sender As Object, e As EventArgs)       MyControl.Label = "You clicked the <b> Click </b> button"    End Sub         Private Sub ResetHandler(sender As Object, e As EventArgs)       MyControl.Text1 = "0"       MyControl.Text2 = "0"    End Sub         Private Sub SubmitHandler(sender As Object, e As EventArgs)       If Int32.Parse(MyControl.Text1) + Int32.Parse(MyControl.Text2) = MyControl.Number Then          MyControl.Label = "<h2> You won a million dollars!!!! </h2>"       Else          MyControl.Label = "Sorry, try again. The numbers you entered don't add up to" & " the hidden number."       End If    End Sub    </script>      <body><h1> The Mystery Sum Game </h1><br>         <form runat=server>              <Custom:EventBubbler id = "MyControl" OnClick = "ClickHandler" OnReset = "ResetHandler" OnSubmit = "SubmitHandler" Number= "10" runat = server/>                                     </form>                       </body>                    </html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.