您可以使用BubbleEventconcept來執行此操作。一個BubbleEvent上升到控制層次結構,直到有人處理它爲止。 GridView和Repeater控件通過它們的Row/ItemCommand事件來完成此操作。
你可以落實到WebUserControl1,把它變成了一個網頁標準事件(如GridView控件一樣):
Class UserControl1 ' Parent
Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean
Dim c as CommandEventArgs = TryCast(e, CommandEventArgs)
If c IsNot Nothing Then
RaiseEvent ItemEvent(sender, c)
Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy
End If
Return False ' Couldn't handle, so let it bubble
End Function
Public Event ItemEvent as EventHandler(Of CommandEventArgs)
End Class
Class UserControlB ' Child
Protected Sub OnClicked(e as EventArgs)
' Raise a direct event for any handlers attached directly
RaiseEvent Clicked(Me, e)
' And raise a bubble event for parent control
RaiseBubbleEvent(Me, New CommandEventArgs("Clicked", Nothing))
End Sub
Protected Sub OnMoved(e as EventArgs)
' Raise a direct event for any handlers attached directly
RaiseEvent Moved(Me, e)
' And raise a bubble event for parent control
RaiseBubbleEvent(Me, New CommandEventArgs("Moved", Nothing))
End Sub
End Class
Class PageA
Sub UserControl1_ItemEvent(sender as Object, e as CommandEventArgs) Handles UserControl1.ItemEvent
Response.Write(sender.GetType().Name & " was " & e.CommandName)
End Sub
End Class
或者,在頁面中直接這樣做。 UserControlB(兒童)是與上面相同,和的UserControl1(母公司)並不需要做什麼特別的 - OnBubbleEvent默認返回false,因此事件冒泡:
Class PageA
Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean
If sender Is UserControlB Then
Dim c as CommandEventArgs = TryCast(e, CommandEventArgs)
If c IsNot Nothing Then
Response.Write(sender.GetType().Name & " was " & c.CommandName)
Else
Response.Write(sender.GetType().Name & " raised an event, with " & e.GetType().Name & " args)
End If
Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy
End If
Return False ' Not handled
End Function
End Class
如果您最初的活動是從服務器控件(如Button.Click),那麼它將被編碼爲已經引發冒泡事件 - 所以UserControlB(Child)不需要做任何事情來將它們傳遞給父類。您只需要爲任何自定義事件調用RaiseBubbleEvent,或者如果您想以某種方式轉換EventArgs。
這正是我試圖找出如何去做的。完美的答案!非常感謝(其他人也很好的回答)。 – 2008-12-02 18:15:33