简体   繁体   中英

Correct item selected upon user pressing enter for a combobox

I have a WPF with a custom combo box that, as the user types, filters the remaining list for words that CONTAIN (not just start with) the user input. Now i would like to press enter, and the first item in the drop down be the selecteditem.

Here is the before :

在此处输入图片说明

Desired behavior: when i press enter from here, DHC becomes the SelectedItem.

What actually happens:

在此处输入图片说明

HEI becomes the selected answer, (probably because it was the only node that started with "HE".

In order to fix this, i attempted to overload the keypress function by including this in the xaml:

<i:Interaction.Triggers>
   <i:EventTrigger EventName="KeyDown" >
      <cmd:EventToCommand Command="{Binding KeyPress}"
         PassEventArgsToCommand="True" />
   </i:EventTrigger>
</i:Interaction.Triggers>

which routes to this in the code:

private void OnDownPress(KeyEventArgs e)
{
   var key = e.Key.ToString().ToLower();
   switch (key)
     {
        case "up":
           break;
        case "down"
           break;
        case "return":
           SelectedNode = NodeTokenList[0];
           UserInput = NodeTokenList[0].FullNodeName;
           break;
     }
 }

Now I tried setting a break point on the return part of the switch statement, I have to press enter 3 times before the switch gets triggered. And even then the text box does not reflect the desired behavior

You can bind the Selected Item in your Model and everytime the filter changes you set the SelectedItem to the first item in the filtered list

what would be a way so that i can navigate using the arrow buttons

if WPF combo box does not support arrow navigation by default you can do something with Command Binding.

First you bind the SelectedIndex property, then the down command will just set SelectedItem = filteredList[SelectedIndex + 1] (with boundary check ofc)

But I remember keyboard navigation should be included with the default Combobox though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM