2014-10-10 53 views
1

我想创建一个Sub,将一个事件连接到一个函数 在此之前,我想要删除旧的事件。删除旧处理程序并连接新的处理程序内部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 
+0

两件事情 - 不正确的地址获取传递给你的'AddHandler'声明摆在首位?你测试过了吗?其次,按钮的签名不像您为DelegateType委托子指定的那样。 – Paul 2014-10-10 08:38:25

+0

第一:不,我甚至不能编译这个。对于第二个:我已经试过了:公共委托子委托类型(ByVal发件人为System.Object,ByVal e为System.EventArgs)在另一个尝试中,我已经删除了Add/RemoveHandler中的AddressOf函数,但编译器告诉我它不能将Delagate类型转换为System.Eventhandler。 – 2014-10-10 08:52:00

+0

我也尝试将newFunctionAdres作为Eventhandler传递。这适用于向按钮添加新事件,但我无法存储此事件处理程序,因此我可以在下次调用时将其从按钮中删除。 – 2014-10-10 09:08:56

回答

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

Thanx!

问题解决了 对于其他成员,这是最后的代码:

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