Autocomplete for ComboBox in WPF anywhere in text (not just beginning)

前端 未结 5 1440
挽巷
挽巷 2020-12-13 18:39

I\'ve got a ComboBox in WPF that I\'ve mucked around with quite a lot (it has a custom template and a custom item template). I\'ve got it to the point now where it is workin

5条回答
  •  青春惊慌失措
    2020-12-13 19:34

    You could try handling the ComboBox's TextInput or PreviewTextInput events, doing the text search yourself, selecting the most appropriate item, and setting "e.Handled = true." Just a thought. Hope this helps!

    edit:

    This works for a single character (i.e. if you enter the letter "j", it will select the first item that contains a "j" or "J"), but I'm sure there's a way to do this with your control. Enjoy!

    private void MyComboBox_PreviewTextInput(object sender, TextCompositionEventArgs e) {
        foreach (ComboBoxItem i in MyComboBox.Items) {
            if (i.Content.ToString().ToUpper().Contains(e.Text.ToUpper())) {
                MyComboBox.SelectedItem = i;
                break;
            }
        }
        e.Handled = true;
    }
    

提交回复
热议问题