简体   繁体   中英

UWP XAML Textbox Focus after Enter

I have a Menu like this:

在此处输入图片说明

I´d like that if the cursor is on ValorInsTextBox (Valor Textbox) and I press Enter, the app call the button InserirBtn_ClickAsync (Inserir Button) and after the process, the cursor come back to PosicaoInsTextBox (Posição Textbox). I made some methods using Key_Down, but something weird happens. Look the code:

private void PosicaoInsTxtBox_KeyDown(Object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        InserirBtn_ClickAsync(sender, e);

        PosicaoInsTxtBox.Focus(FocusState.Programmatic);
    }
}

private void ValorInsTxtBox_KeyDown(Object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        InserirBtn_ClickAsync(sender, e);

        if (PosicaoInsTxtBox.IsEnabled)
        {
            PosicaoInsTxtBox.Focus(FocusState.Programmatic);
        }
        else
        {
            ValorInsTxtBox.Focus(FocusState.Programmatic);
        }
    }
}

When I debug the code, I press Enter when the ValorInsTextBox is on focus, and the method ValorInsTextBox_KeyDown starts and everything goes well. And when it arrives on line:

PosicaoInsTxtBox.Focus(FocusState.Programmatic);

it goes to execute the method PosicaoTextBox_KeyDown and starts to execute it. I don´t know why! Anyone can help me?

You could set the Handled property of the KeyRoutedEventArgs to true in the ValorInsTxtBox_KeyDown event handler to prevent the PosicaoInsTxtBox_KeyDown event handler from being invoked:

private void ValorInsTxtBox_KeyDown(Object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        InserirBtn_ClickAsync(sender, e);

        if (PosicaoInsTxtBox.IsEnabled)
        {
            PosicaoInsTxtBox.Focus(FocusState.Programmatic);
        }
        else
        {
            ValorInsTxtBox.Focus(FocusState.Programmatic);
        }
    }
    e.Handled = true;
}

And do the same in the PosicaoInsTxtBox_KeyDown event handler to prevent it from being invoked again when you press ENTER in the Posicao" TextBox:

private void PosicaoInsTxtBox_KeyDown(Object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        InserirBtn_ClickAsync(sender, e);

        PosicaoInsTxtBox.Focus(FocusState.Programmatic);
    }
    e.Handled = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM