Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"/> 
like image 468
NetSide Avatar asked Feb 05 '10 09:02

NetSide


2 Answers

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.

like image 197
MoominTroll Avatar answered Oct 17 '22 20:10

MoominTroll


Assuming your items are sorted alphabetically, simply setting IsTextSearchEnabled="True" should jump to the items starting with the letter (or letters) you type into the ComboBox.

Here is an example of one of my ComboBoxes, I have simplified the bindings as it's clearly not the important part here...

<ComboBox ItemsSource="{Binding MyObjectList}"
          DisplayMemberPath="Description"
          SelectedValuePath="Code"
          IsTextSearchEnabled="True"/>

This works perfectly for selecting a value from the list, however, the search value you type will not display in the TextBox part of the control as I have IsEditable set to false.

If anyone would like to explain why this has been voted down it would be appreciated, I don't see any problem with the answer I've provided and don't see why I deserve to lose reputation when I'm only trying to help (and have provided a reasonable answer!)

like image 37
TabbyCool Avatar answered Oct 17 '22 20:10

TabbyCool