2016-07-30 83 views
0

我將使用屬性來保留click子地址,然後將其分配給AddRow()子中的每個按鈕。出現問題時,我得到了以下錯誤:保留屬性中的子地址

錯誤1

Method 'Public Property ClickEvent As Button_Click' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As System.EventArgs)'.

Private Sub Button_Click(sender As Object, e As EventArgs) 
    'do somthing 
End Sub 

Class CustomClass 
    Public Fields As New List(Of FieldsDefinition)() 

    Class FieldsDefinition 
     Public Delegate Sub Button_Click(sender As System.Object, e As System.EventArgs) 

     Public __ClickEventValue As Button_Click 
     Public Property ClickEvent() As Button_Click 
      Get 
       Return __ClickEventValue 
      End Get 

      Set(ByVal value As Button_Click) 
       __ClickEventValue = value 
      End Set 
     End Property 
    End Class 

    Public Sub AddRow() 
     For Each field As FieldsDefinition In Fields 
      Dim ctrl As New TextBox 
      AddHandler ctrl.Click, AddressOf field.ClickEvent 
     Next 
    End Sub 
End Class 

回答

0

2點的變化:

  1. 取出AddressOf,因爲你不希望處理程序成爲ClickEvent屬性本身,您希望它成爲返回的委託。

  2. AddHandler將預期類型EventHandler類型的處理程序。因此,請刪除Button_Click委託聲明,並用EventHandler替換對它的任何參考。

代碼:

Private Sub Button_Click(sender As Object, e As EventArgs) 
    'do somthing 
End Sub 

Class CustomClass 
    Public Fields As New List(Of FieldsDefinition)() 

    Class FieldsDefinition 
     ' removed Button_Click delegate declaration here 

     Public __ClickEventValue As EventHandler 'changed Button_Click to EventHandler here 
     Public Property ClickEvent() As EventHandler 'changed Button_Click to EventHandler here 
      Get 
       Return __ClickEventValue 
      End Get 

      Set(ByVal value As EventHandler) 'changed Button_Click to EventHandler here 
       __ClickEventValue = value 
      End Set 
     End Property 
    End Class 

    Public Sub AddRow() 
     For Each field As FieldsDefinition In Fields 
      Dim ctrl As New TextBox 
      AddHandler ctrl.Click, field.ClickEvent 'removed AddressOf here 
     Next 
    End Sub 
End Class 
+0

Thanks.It工作這麼好! –