Search code examples
wpfvb.netcomboboxselectionchanged

How to fire an event when making a selection of an editable combobox?


I have a ComboBox that is databound to an ObservableCollection of strings. The ComboBox is also editable, so you can either enter in your own value or select one from the list. The issue I'm running into is the index of SelectedItem seems to be the index of the last item you selected when you've entered in your own value in the ComboBox, though it's -1 when you have IsTextSearchEnabled set to true.

The problem is, if someone entered their own value and then decide to instead select the item on the ComboBox that had been selected before, the index doesn't change so the SelectionChange event doesn't fire. How could I get an event to fire in this situation?


Solution

  • Test this... I hope this helps:

    Dim oldSEL As String = ""
    
    'always checking while you move your mouse over the combobox (when altering selection) and using the keyboard to (alter selection)
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.MouseMove, ComboBox1.KeyPress
        Dim currentSEL As String = ComboBox1.SelectedText
        If Not (oldSEL = "" And currentSEL = oldSEL) Then
            fire()
            oldSEL = currentSEL
        End If
    End Sub
    
    Private Sub fire()
        Trace.Write("text selected changed")
    End Sub
    

    You should change all the Combobox1 to your liking.