Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move to next textbox when 'Enter' key is pressed instead of submit (Windows Phone)

Tags:

c#

xaml

uwp

I have a simple form and I would like that when the user presses enter in his phone keyboard the cursor will move to the next textbox. Can this be done in Universal Windows Apps? In android the keyboard shows a Next/Done key to navigate in the form elements.

enter image description here

like image 566
Bruno Medina Avatar asked Jan 19 '16 23:01

Bruno Medina


People also ask

How do I move to the next textbox pressing key?

If you want to go next control (textbox, comboBox, dateTimePicker..etc) you can press Enter Key or Down Key and if you want go to previous control you can press Up Key. If the control is comboBox or dateTimePicker we can use Control Key plus Up Key to go to previous Control and use only Enter Key to go to next Control.


1 Answers

You can use FocusManager to move the focus programmatically.

Use the KeyDown event of the TextBox container, let's say, a StackPanel, to listen to your keyboard event. So your code would work like this way

    private void stackPanel_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Enter)
        {
            if (FocusManager.GetFocusedElement() == inputTextBox) // Change the inputTextBox to your TextBox name
            {
                FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
                FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
            }
            else
            { 
                FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
            }

            // Make sure to set the Handled to true, otherwise the RoutedEvent might fire twice
            e.Handled = true;
        }
    }

For more details on FocusManager, see to https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.input.focusmanager.trymovefocus

For more details on KeyDown, see to https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.keydown

like image 174
Jackie Avatar answered Nov 10 '22 16:11

Jackie