29
votes

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 working pretty much how I want it, except that when I type into the ComboBox it is doing the filtering for me, but only filters assuming what I type starts the name of the item in the ComboBox.

For example if I have an item in the ComboBox called "Windows Media Player" it will only find it if I start typing "Windows Media..." and it won't find it if I start typing "Media Play...". Is there any way around this? Can I set a property somewhere to tell it to search in the whole string rather than just using StartsWith()?

If not, what would be the best way to go about making it do this by myself? Is there some way to take the original control and basically just change the call to StartsWith() to a call to Contains(), or would I have to go far more low-level?

5

5 Answers

39
votes

The combobox now supports autocomplete, just make sure in the xaml for the combobox put

IsEditable="True"
8
votes

Check out the following article in CodeProject: A Reusable WPF Autocomplete TextBox

4
votes

As far as I know there's no way to force standard ComboBox to behave this way by just changing a setting. So you'll have to implement your own combo box derivative for that or search for ready made 3rd party control (I believe there are plenty of them).

4
votes

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;
}
2
votes

WPF Combo box don't support Autocomplete

Here is a sample that allows you to do this in an indirect manner, by applying a filter to the items.

See http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/cec1b222-2849-4a54-bcf2-03041efcf304/