Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move to the next control on enter/return press in Windows 8 Store application

I have a windows 8 store application with numerous textboxes. When I press enter on the keyboard I'd like the focues to move to the next control.

How can I do this?

Thanks

like image 548
Sun Avatar asked Jul 12 '13 14:07

Sun


2 Answers

You can handle the KeyDown/KeyUp events on your TextBoxes (depending on whether you want to go to the next one at the beginning or end of the key press).

Example XAML:

<TextBox KeyUp="TextBox_KeyUp" />

Code Behind:

    private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
    {
        TextBox tbSender = (TextBox)sender;

        if (e.Key == Windows.System.VirtualKey.Enter)
        {
            // Get the next TextBox and focus it.

            DependencyObject nextSibling = GetNextSiblingInVisualTree(tbSender);
            if (nextSibling is Control)
            {
                // Transfer "keyboard" focus to the target element.
                ((Control)nextSibling).Focus(FocusState.Keyboard);
            }
        }
    }

Full example code including code for the GetNextSiblingInVisualTree() helper method: https://github.com/finnigantime/Samples/tree/master/examples/Win8Xaml/TextBox_EnterMovesFocusToNextControl

Note that calling Focus() with FocusState.Keyboard shows the dotted focus rect around elements that have such a rect in their control template (e.g. Button). Calling Focus() with FocusState.Pointer does not show the focus rect (you are using touch/mouse, so you know which element you are interacting with).

like image 195
Patrick Finnigan Avatar answered Sep 27 '22 19:09

Patrick Finnigan


I made a slight improvement to the "GetNextSiblingInVisualTree" function. This version searches for the next TextBox instead of the next object.

    private static DependencyObject GetNextSiblingInVisualTree(DependencyObject origin)
    {
        DependencyObject parent = VisualTreeHelper.GetParent(origin);

        if (parent != null)
        {
            int childIndex = -1;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                if (origin == VisualTreeHelper.GetChild(parent, i))
                {
                    childIndex = i;
                    break;
                }
            }

            for (int nextIndex = childIndex + 1; nextIndex < VisualTreeHelper.GetChildrenCount(parent); nextIndex++ )
            {
                DependencyObject currentObject = VisualTreeHelper.GetChild(parent, nextIndex);

                if( currentObject.GetType() == typeof(TextBox))
                {
                    return currentObject;
                }
            }
        }

        return null;
    }
like image 24
Paul MaC Avatar answered Sep 27 '22 20:09

Paul MaC