1
votes

I am building a XAML app (winrt) to be used in enterprise. Some forms in the app can be complex: some inputs gets shown/hidden depending on other inputs. I would like to control the tab key navigation using a behavior on all inputs (TextBox, PasswordBow, ComboBox...) to optimize the user activity.

I subscribed to the KeyUp event of the TextBox but the event is not raised when the user strikes the Tab key. As a consequence, the next element in the visual tree is given keyboard focus.

I found not method to override like the winform's IsInputKey.

How can I subscribe to the use of the Tab key on a TextBox?

2

2 Answers

2
votes

Is looks like the newly focus element receives the KeyUp event.

What I did is subscribe to the KeyDown event, checked for the Tab key and marked the event as handled.

protected override void OnAttached()
{
    var textBox = (TextBox)this.AssociatedObject;
    textBox.KeyDown += this.OnKeyDown;
    textBox.KeyUp += this.OnKeyUp;
    // don't forget to unsubscribe in OnDetached
}

private void OnKeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Tab && !e.Handled)
    {
        e.Handled = this.Work(sender, e);
    }
}

private void OnKeyUp(object sender, KeyRoutedEventArgs e)
{
    if (e.Key != VirtualKey.Tab && !e.Handled)
    {
        e.Handled = this.Work(sender, e);
    }
}

Here is the method that does the focusing work. The code was in OnKeyUp before I knew how to do.

/// <returns>true if an action has been performed (focus next or execute command)</returns>
private bool Work(object sender, KeyRoutedEventArgs e)
{
    var isEnterKey = e.Key == VirtualKey.Enter;
    var isTabKey = e.Key == VirtualKey.Tab;

    if (/* there is something else to focus */)
    {
        // focus it
        return true;
    }

    return false;
}
0
votes

My problem was that the Tab virtual key wasn't being received in the KeyUp event, while other keys (Esc,Enter, alphanumeric keys) were. I just changed it to a KeyDown with the same handler. The difference seems to be imperceptible to the user.