2011-04-27 33 views
0

我有一個MyUserControl其中我有Button1Button2按鈕。在VB.NET中重定向事件

我需要「委託」該按鈕點擊分別到MyUserControl的Button1Click事件和Button2Click事件。

貝婁是一個存根我真的不知道整理...

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 

我不知道如果我需要WithEvents的按鈕聲明,以及如何實現RaiseEvent部分...

回答

1

如果我理解您的設置正確,那麼您可能只想處理這些事件並將它們傳遞給自定義事件。就像這樣:

' 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 

編輯:

這裏會發生什麼是事件的一個簡單的中繼,它打破了事件鏈,並觸發它在自己之間的事件。

MyUserControl 
+-> Custom Event: Button1Click 
+-> Control: Button1 

現在,如果Button1被點擊,事件鏈看起來像這樣:

Button1.CLick() -> Calling EventHandlers 
+-> MyUserControl.Button1_Click(Object, EventArgs) -> Raises its own Event 
     +-> Parent.MyUserControl_Button1Click(Object, EventArgs) 
      ' Application Logic executes here 
+0

會是什麼,如果我使用'AddHandler的myUserControl.Button1Click,AddressOf myMethod'?我會訂閱該按鈕上的鼠標點擊嗎?不知道... – serhio 2011-04-27 11:47:40

+0

@serhio:是的,這應該工作。因爲'myUserControl'接收到這個硬連線的'Button1.Click'事件並且將它傳遞給它自己。 – Bobby 2011-04-27 11:57:09

+0

測試....似乎工作。我有點驚訝...但如果它工作,很酷) – serhio 2011-04-27 11:57:41