Redirect Events in VB.NET
I have a MyUserControl
in which I have Button1
and Button2
buttons.
I need to "delegate" that button clicks to the MyUserControl's Button1Click
event and Button2Click
event respectively.
Bellow is a stub I don't r开发者_如何学Pythoneally know finishing...
Private WithEvents Button1 As Button
Private WithEvents Button2 As Button
Public Custom Event Button1Click As Eventhandler
AddHandler(ByVal value As EventHandler)
AddHandler Me.Button1.Click, value
End AddHandler
RemoveHandler(ByVal value As EventHandler)
RemoveHandler Me.Button1.Click, value
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
Me.Button1.Invoke(???)
End RaiseEvent
End Event
I wonder if I need the WithEvents
in the buttons declaration, and how to achieve the RaiseEvent
part...
If I understand your setup correct, you might want to just handle the events and pass them on to a custom event. Like this:
' This is defined in your control
Public Event Button1Click(ByVal sender As Object, ByVal e As EventArgs)
' Other stuff here
' This is the handler for the Button1.Click Event.
Public Sub Button1_Click(ByVal sender as Object, ByVal e As EventArgs) Handles Button1.Click
' Raise our custom event to the outside
RaiseEvent Button1Click(Me, e)
End Sub
Edit:
What happens here is a simple relaying of events, it breaks the event-chain and fires it's own event in between.
MyUserControl
+-> Custom Event: Button1Click
+-> Control: Button1
Now if Button1
gets clicked, the event chain is looking like this:
Button1.CLick() -> Calling EventHandlers
+-> MyUserControl.Button1_Click(Object, EventArgs) -> Raises its own Event
+-> Parent.MyUserControl_Button1Click(Object, EventArgs)
' Application Logic executes here
精彩评论