开发者

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

开发者 https://www.devze.com 2023-01-19 17:53 出处:网络
I have wpf UserControl containing a combobox and a textbox in a row. Currently the only way to move between the components is to tab between them, but I would like to also be able to switch from the c

I have wpf UserControl containing a combobox and a textbox in a row. Currently the only way to move between the components is to tab between them, but I would like to also be able to switch from the combobox to the textbox using the left and right arrow keys.

It is not as easy as just slapping an eventhandler on the keyup event.

void ComboKeyUp( object sender, KeyEventArgs e )
{
    if( e.Key == Key开发者_如何学C.Right)
    {
        e.Handled = true;
        textbox.Focus();
    }
}

...because the combo will change value despite the event being reported as handled.

Is there a way to do this that doesn't simultaneously break the up/down selection of items in the combo box?


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.

0

精彩评论

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