Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting WPF ComboBoxItem using Tab Key

Tags:

wpf

The WPF ComboBox doesn't select item when you hit Tab Key. You have to either hit "Enter" or click on the item with your mouse to select it!

This is how I expect it to work:

  1. Expand the ComboBox
  2. Use the up/down arrow keys to find the item you want to select.
  3. Press the "tab" key on the current item to select it and then move on to the next field.

In reality, it cycles through all of the ComboBoxItems in the ComboBox when you hit the tab key.

like image 962
prawin Avatar asked Aug 31 '11 09:08

prawin


1 Answers

In case anyone comes here looking for an example (as I was,) here is the contents of a KeyEvent event handler that works for me:

if (e.Key == Key.Tab || e.Key == Key.Enter)
{
    var comboBox = sender as ComboBox;
    var newValue = (e.OriginalSource as ComboBoxItem)?.DataContext;
    if (newValue != null)
    {
        comboBox.SelectedItem = newValue;
    }
    comboBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
like image 152
Mark Avenius Avatar answered Oct 30 '22 13:10

Mark Avenius