开发者

Selecting WPF ComboBoxItem using Tab Key

开发者 https://www.devze.com 2023-04-01 17:30 出处:网络
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!

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 ComboBo开发者_StackOverflow社区xItems in the ComboBox when you hit the tab key.


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));
}


Tab is caught by the KeyUp event, and the only way to keep track of the currently highlighted item while the comboBox's Drop down list is opened is to modify the textbox in the control template, so that you can access the value that is "selected" and assign that as selected after you hit the tab key.

It isn't the most enjoyable thing to do, but it's the only way you'll get to enforce the behavior you want to use, other than by making a completely different control by yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消