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

独自空忆成欢 提交于 2019-11-28 02:33:37

问题


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"/> 

回答1:


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.




回答2:


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!)




回答3:


All I had to do was add the following:

TextSearch.TextPath="<what ever you bound to goes here> ie:State or name "


来源:https://stackoverflow.com/questions/2206069/how-to-select-item-by-typing-a-keyboard-letter-key-in-wpf-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!