How to select item by typing a keyboard letter key in WPF combobox?

NetSide picture NetSide · Feb 5, 2010 · Viewed 13.3k times · Source

I have a WPF ComboBox and I want to go to items that start with (for example) "e" in the ComboBox when I type that letter. How?

My XAML code:

<ComboBox ItemsSource="{Binding Roles}" SelectedValuePath="Id"
          ItemTemplate="{StaticResource ComboBoxDisplayName}"
          SelectedItem="{Binding SelectedRole}"
          Width="150"/> 

Answer

MoominTroll picture MoominTroll · Feb 5, 2010

EDIT: I'm guessing you have an ItemTemplate that looks a little like this:

<StackPanel>
    <TextBlock Text="{Binding Path=Foo}" />
    <TextBlock Text="{Binding Path=Bar}" />
</StackPanel>

If you want to search on Foo, then try...

<ComboBox IsEditable = "True" TextSearch.TextPath = "Foo" />

By default a ComboBox has a kind of autocomplete that finds matches based on first letter - assuming your source is sorted alphabetically this will shift the selected item to the section that (for example) starts with "e".

Catching KeyDown to force the dropdown to open might be useful if you expect several entries starting with the same letter.