views:

22

answers:

2

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.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?

+1  A: 

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"

Andrey Gordeyev
+1  A: 

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

Zaz