code_junkie

“Re-Raising” Custom Events in .NET (ASP.NET in this case)

Nov 12th, 2011
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. Class UserControl1 ' Parent
  2. Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean
  3. Dim c as CommandEventArgs = TryCast(e, CommandEventArgs)
  4. If c IsNot Nothing Then
  5. RaiseEvent ItemEvent(sender, c)
  6. Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy
  7. End If
  8. Return False ' Couldn't handle, so let it bubble
  9. End Function
  10.  
  11. Public Event ItemEvent as EventHandler(Of CommandEventArgs)
  12. End Class
  13.  
  14. Class UserControlB ' Child
  15. Protected Sub OnClicked(e as EventArgs)
  16. ' Raise a direct event for any handlers attached directly
  17. RaiseEvent Clicked(Me, e)
  18. ' And raise a bubble event for parent control
  19. RaiseBubbleEvent(Me, New CommandEventArgs("Clicked", Nothing))
  20. End Sub
  21.  
  22. Protected Sub OnMoved(e as EventArgs)
  23. ' Raise a direct event for any handlers attached directly
  24. RaiseEvent Moved(Me, e)
  25. ' And raise a bubble event for parent control
  26. RaiseBubbleEvent(Me, New CommandEventArgs("Moved", Nothing))
  27. End Sub
  28. End Class
  29.  
  30. Class PageA
  31. Sub UserControl1_ItemEvent(sender as Object, e as CommandEventArgs) Handles UserControl1.ItemEvent
  32. Response.Write(sender.GetType().Name & " was " & e.CommandName)
  33. End Sub
  34. End Class
  35.  
  36. Class PageA
  37. Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean
  38. If sender Is UserControlB Then
  39. Dim c as CommandEventArgs = TryCast(e, CommandEventArgs)
  40. If c IsNot Nothing Then
  41. Response.Write(sender.GetType().Name & " was " & c.CommandName)
  42. Else
  43. Response.Write(sender.GetType().Name & " raised an event, with " & e.GetType().Name & " args)
  44. End If
  45. Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy
  46. End If
  47. Return False ' Not handled
  48. End Function
  49. End Class
  50.  
  51. Public Partial Class TestPage
  52. Inherits Page
  53.  
  54. Public Sub PerformAction()
  55. 'Whatever needs to be done on Page A
  56. End Sub
  57. End Class
  58.  
  59. Public Partial Class TestControl
  60. Inherits UserControl
  61.  
  62. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  63. 'This will call the Page, obviously this will only
  64. 'work when the control is on TestPage
  65. CType(Page, TestPage).PerformAction()
  66. End Sub
  67. End Class
Add Comment
Please, Sign In to add comment