当它 'jumping' 到 TextBox WPF 网格时,在 TextBox 上触发事件 KeyDown 的问题

Issue with firing event KeyDown on TextBox when it's 'jumping' to a TextBox WPF Grid

我有一个网格,其中包含几个彼此下方的文本框:

回车需要从txt1跳到txt2,从txt2跳到txt3等等,我是这样解决的:

private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
{
    try
    {
        if (e.Key == Key.Enter)
        {
            UIElement element = e.Source as UIElement;

            element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            //e.Handled = true;

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

我的问题在这里,在每个 txt 框上按 Enter 我应该从另一个 txtBoxes 计算一些东西,当我在 txt1 上按 enter 时它会跳到 txt2 并立即调用 txt2_KeyDown 事件,这是我想避免的。当我在 txt2 上 'standing' 和按回车键时,我想调用 txt2_KeyDown 事件..

即:

private void txt2_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        try
        {

            CalculateSomethingFromOtherTextBoxes();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

当我在 txt1 上 'standing' 并且我想按 Enter 跳转到 txt2 时,上面的代码被触发,我怎么能 'jump' 而不调用 txt2 KeyDown 事件 如果我没有当我真的 'standing' 在 'txt2'.

时按 Enter

谢谢大家, 干杯

问题是因为您附加到文本框的 KeyDown 事件。

相反,删除此事件并添加 PreviewKeyDown 事件。

所以,你的方法签名应该是这样的:

private void txt2_PreviewKeyDown(object sender, KeyEventArgs e)
{
   if (e.Key == Key.Return)
        {
            try
            {

               CalculateSomethingFromOtherTextBoxes();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
}

我测试了它,它按预期工作。

And my issue is here, on each of txt boxes by pressing Enter I should calculate something from another txtBoxes, and when I press enter on txt1 it is gonna jump on txt2 and immediatelly call txt2_KeyDown event, which I want to avoid.. I want to call txt2_KeyDown event when I'm 'standing' on txt2 and when I press enter..

那么您可以处理 "txt2" 的 LostKeyboardFocus 事件,而不是处理 KeyDown 事件:

private Key key;
private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    key = e.Key;
    if (key == Key.Enter)
    {
        UIElement element = e.OriginalSource as UIElement;
        element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }

}

private void txt2_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if (key == Key.Enter)
    {
        CalculateSomethingFromOtherTextBoxes();
    }
}