UWP XAML 输入后的文本框焦点

UWP XAML Textbox Focus after Enter

我有这样的菜单:

我希望如果光标位于 ValorInsTextBox(Valor 文本框)上并且我按下 Enter,应用程序将调用按钮 InserirBtn_ClickAsync(Inserir 按钮),并且在此过程之后,光标返回到 PosicaoInsTextBox (Posição 文本框)。 我使用 Key_Down 制作了一些方法,但发生了一些奇怪的事情。看代码:

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);
        }
    }
}

当我调试代码时,我在 ValorInsTextBox 处于焦点上时按 Enter,方法 ValorInsTextBox_KeyDown 启动并且一切顺利。当它上线时:

PosicaoInsTxtBox.Focus(FocusState.Programmatic);

它去执行方法PosicaoTextBox_KeyDown并开始执行它。我不知道为什么!谁能帮帮我?

您可以在 ValorInsTxtBox_KeyDown 事件处理程序中将 KeyRoutedEventArgs 的 Handled 属性 设置为 true 以防止调用 PosicaoInsTxtBox_KeyDown 事件处理程序:

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;
}

并在 PosicaoInsTxtBox_KeyDown 事件处理程序中执行相同操作,以防止当您在 Posicao 中按 ENTER 时再次调用它" 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;
}