AbsoluteSith
AbsoluteSith

Reputation: 1967

KeyDown event doesn't work when ComboBox is opened?

Why is the KeyDown event not triggered when the ComboBox dropdown is opened? Is there any way to trigger this.

I'm trying to use KeyDown event to check which key is pressed and automatically selecting an item from the ComboBox which starts with the pressed character simulating a partial Auto Complete feature. But this does not work when the ComboBox is opened.

Code:

<ComboBox x:Name="statusComboBox" KeyDown="ComboBox_KeyDown"/>

statusComboBox.ItemsSource = inspectionStatusComboList;

private void ComboBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
    ComboBox box = sender as ComboBox;
    int index = -1;
    string key = e.Key.ToString();

    if (key.Length == 1)
    { 
       switch(box.Name)
       {
          case "statusComboBox":
                    index = inspectionStatusComboList.IndexOf(inspectionStatusComboList.FirstOrDefault(x => x.StartsWith(key)));
                    break;
       }
       box.SelectedIndex = index;
    }
}

Here is a clip of what I'm trying to achieve. enter image description here

Upvotes: 3

Views: 1291

Answers (2)

Filip Skakun
Filip Skakun

Reputation: 31724

I can imagine the dropdown popup getting focus, so you'd have to get access to that and subscribe to key events on that as well. See the template here for reference. You could try subscribing to these events on the Popup or PopupBorder elements.

You could also use the AutoCompleteTextBox from my toolkit instead.

Upvotes: 2

Mikael Puusaari
Mikael Puusaari

Reputation: 1054

Try changing KeyRoutedEventArgs to KeyEventArgs and see you get it going, since we cant see the rest of your code to see if you create the routes

Upvotes: 0

Related Questions