Can I navigate into and out of a wpf combo box using arrow keys instead of tab?

坚强是说给别人听的谎言 提交于 2019-12-06 07:53:00

I have created the combobox with textboxes:

<ComboBox Width="100" Height="25"  PreviewKeyDown="ComboboxPreviewKeyDown">
  <ComboBox.Items> 
    <TextBox Text="Item 1"/>
    <TextBox Text="Item 2"/>
    <TextBox Text="Item 3"/>
  </ComboBox.Items>
</ComboBox>

Then added handler:

    private void ComboboxPreviewKeyDown(object sender, KeyEventArgs e)
    {
        Action<FocusNavigationDirection> moveFocus = focusDirection => {
            e.Handled = true;
            var request = new TraversalRequest(focusDirection);        
            var focusedElement = Keyboard.FocusedElement as UIElement;
            if (focusedElement != null)
                focusedElement.MoveFocus(request);
        };

        if (e.Key == Key.Down)
            moveFocus(FocusNavigationDirection.Next);
        else if (e.Key == Key.Up)
            moveFocus(FocusNavigationDirection.Previous); 
    }

Now "Up" and "Down" buttons behavior are the same as "Tab" and "Shift+Tab"

It turns out there is a gotcha, you have subscribe to the KeyDown event instead.

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