删除旧处理程序并在Sub中连接新的处理程序

时间:2014-10-10 08:10:06

标签: vb.net events handler

我想创建一个将事件连接到函数的Sub 在此之前我想删除旧事件。

这是我到目前为止所知道的,我知道它必须是朝这个方向发展的 但我不断收到错误 BC30577:'AddressOf'操作数必须是方法的名称(没有括号)。

    Delegate Sub DelegateType()

    Private Sub ConnectButtonWithEvent(ByRef Button As CommandButton, ByRef newFunctionAdres As DelegateType)   
        Static OldEvent As DelegateType
        Static OldButton As CommandButton   

        If Not OldButton Is Nothing Then
            RemoveHandler OldButton.Click, AddressOf OldEvent
        End If 

        AddHandler Button.Click, AddressOf newFunctionAdres 

        OldEvent = AddressOf newFunctionAdres
        OldButton = Button
    End Sub

2 个答案:

答案 0 :(得分:1)

以下为我工作......

Private Sub test(ByVal btn As Button, ByVal fad As EventHandler)
    AddHandler btn.Click, fad
End Sub


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    test(tb, AddressOf ClickHandler)
End Sub

Private Sub ClickHandler(ByVal sender As Object, ByVal e As EventArgs)
    'Do nothing
End Sub

问题只是您用来传递委托的参数的类型 - 应该是EventHandler

答案 1 :(得分:1)

感谢名单!

修复了它 对于其他成员,这是最终代码:

Private Sub ConnectButtonWithEvent(ByRef Button As VisiWinNET.Forms.CommandButton, ByRef     newFunctionAdres As EventHandler)

        Static OldEvent As EventHandler         
        Static OldButton As VisiWinNET.Forms.CommandButton

        If Not OldButton Is Nothing Then
            RemoveHandler OldButton.Click, OldEvent
        End If

        AddHandler Button.Click, newFunctionAdres

        OldEvent = newFunctionAdres
        OldButton = Button
    End Sub