vb.net子类化ComboBox - 尝试创建可以取消的SelectedIndexChanging事件

时间:2016-09-10 22:32:45

标签: vb.net combobox event-handling subclass selectedindexchanged

我目前正在尝试在vb中实现来自此线程How can I handle ComboBox selected index changing?的第二个响应(建议继承ComboBox以引入新的SelectedIndexChangingEvent的响应)。事件处理程序

Private Sub MyComboBox1_SelectedIndexChanging(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyComboBox1.SelectedIndexChanging
        MsgBox("Changing")
End Sub

永远不会受到打击。我认为它与我正在初始化selectedIndexChanging(小写首字母)变量的方式有关。有什么想法吗?

Imports System.ComponentModel

Public Class MyComboBox
    Inherits ComboBox

    Public Event SelectedIndexChanging as CancelEventHandler
    Public LastAcceptedSelectedIndex As Integer

    Public Sub New()
        LastAcceptedSelectedIndex = -1
    End Sub

    Protected Sub OnSelectedIndexChanging(e As CancelEventArgs)
        Dim selectedIndexChanging as CancelEventHandler = SelectedIndexChanging
        If Not SelectedIndexChanging Is Nothing Then
            selectedIndexChanging(Me, e)
        End If
    End Sub

    Protected Overrides Sub OnSelectedIndexChanged(e As EventArgs)
        If LastAcceptedSelectedIndex <> SelectedIndex Then
            Dim cancelEventArgs = New CancelEventArgs
            OnSelectedIndexChanging(cancelEventArgs)
            If Not cancelEventArgs.Cancel Then
                LastAcceptedSelectedIndex = SelectedIndex
                MyBase.OnSelectedIndexChanged(e)
            Else 
                SelectedIndex = LastAcceptedSelectedIndex
            End If
        End If
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

VB处理的事件声明与C#略有不同。 VB RaiseEvent关键字有效地生成您试图为`OnSelectedIndexChanging&#39;翻译的代码。方法。

正确的VB实现将是:

 Protected Sub OnSelectedIndexChanging(e As CancelEventArgs)
      RaiseEvent SelectedIndexChanging(Me, e)
 End Sub

您可以按照原始模式,使用隐藏变量VB创建的是真正的CancelEventHandler变量。这些隐藏变量遵循eventName 事件的命名模式。因此,真正的CancelEventHandler变量名为:SelectedIndexChangingEvent。

 Protected Sub OnSelectedIndexChanging(e As CancelEventArgs)
      Dim selectedIndexChanging As CancelEventHandler = Me.SelectedIndexChangingEvent

      If Not selectedIndexChanging Is Nothing Then
            selectedIndexChanging(Me, e)
      End If
 End Sub