为将 ComboBox 作为参数传递的不同 ComboBox 删除和添加事件处理程序

Removing and adding event handlers for different ComboBoxes where the ComboBox is passed as a parameter

我有一个方法将 ComboBox 作为参数,然后向其中添加数据。添加数据时,将触发 SelectedIndexChangedEvent。有没有一种方法,在被调用的方法中,我可以为作为参数传递的任何 ComboBox 删除上面的事件处理程序,然后在方法的末尾添加?我知道如何删除和添加特定的处理程序,但无法根据传递的 ComboBox 弄清楚该怎么做。

方法如下..

Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
    'Remove handler for cboBox
    'Do stuff that would otherwise cause the event handler to execute
    'Add handler for cboBox
End Sub 

我有 4 个组合框 - 删除所有 4 个事件处理程序然后在代码末尾再次添加它们会更容易吗?但是,我想知道这是否可行,以便我将来可以申请可重用代码

这是一种方法:

' these happen to map to the same event handler
Private cb1Event As EventHandler = AddressOf cbx_SelectedIndexChanged
Private cb2Event As EventHandler = AddressOf cbx_SelectedIndexChanged

然后使用时:

PopulateComboBox(cb1, items, cb1Event)
PopulateComboBox(cb2, items, cb2Event) 
' or
PopulateComboBox(cb3, items, AddressOf cbx_SelectedIndexChanged) 

将声明该方法:

Private Sub PopulateComboBox(cboBox As ComboBox, 
                            items As String, ev As EventHandler)

就个人而言,既然你知道所涉及的 CBO,我会在通话前这样做:

RemoveHandler cb1.SelectedIndexChanged, AddressOf cbx_SelectedIndexChanged
PopulateComboBox(cb1, items)
AddHandler cb1.SelectedIndexChanged, AddressOf cbx_SelectedIndexChanged

传递所有信息以对其他事物执行某些操作并使其可以执行您知道需要执行的操作并不会带来太多好处。

最基本的方法是这样做:

Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
    RemoveHandler cboBox.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
    'Do stuff that would otherwise cause the event handler to execute
    AddHandler cboBox.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged

End Sub

另一个在某些情况下可能更好的选择是:

Private _ignoreComboBox As ComboBox = Nothing

Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
    _ignoreComboBox = cboBox
    'Do stuff that would otherwise cause the event handler to execute
    _ignoreComboBox = Nothing
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If sender Is Not _ignoreComboBox Then

    End If
End Sub

或者,同时处理多个组合框:

Private _ignoreComboBoxes As List(Of ComboBox) = New List(Of ComboBox)()

Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
    _ignoreComboBoxes.Add(cboBox)
    'Do stuff that would otherwise cause the event handler to execute
    _ignoreComboBoxes.Remove(cboBox)
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If Not _ignoreComboBoxes.Contains(DirectCast(sender, ComboBox)) Then

    End If
End Sub