2

我有一个简单的应用程序(一个带有 6 个按钮的网格 - 2 行 3 个 - 用于测试)并且正在按如下方式处理左右箭头键

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        FocusNavigationDirection focusDirection = new System.Windows.Input.FocusNavigationDirection();

        switch (e.Key)
        {
            case Key.Left:
                focusDirection = System.Windows.Input.FocusNavigationDirection.Left;
                break;
            case Key.Right:
                focusDirection = System.Windows.Input.FocusNavigationDirection.Right;
                break;
            default:
                break;
        }
        TraversalRequest request = new TraversalRequest(focusDirection);

        // Gets the element with keyboard focus.
        UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

        // Change keyboard focus.
        if (elementWithFocus != null)
        {
            elementWithFocus.MoveFocus(request);
        }

    }

不幸的是,这并没有像我预期的那样表现,因为焦点似乎总是在与 FocusNavigationDirection 指定的方向相反的方向上移动。

关于为什么会这样的任何想法?MSDN 文档对如何定义“左侧”有点模糊。

如果需要,我还将每个按钮的制表位定义为 1 到 6。

4

2 回答 2

3

为什么在可以使用“this”(窗口自己的范围)时需要获取 elementWithFocus?

我稍微修改了你的代码,它对我有用:

    private void Window_OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Left:
                this.MoveFocus(FocusNavigationDirection.Previous);
                break;
            case Key.Right:
                this.MoveFocus(FocusNavigationDirection.Next);
                break;
            default:
                break;
        }
    }

    private void MoveFocus(FocusNavigationDirection direction)
    {
        var request = new TraversalRequest(direction);
        this.MoveFocus(request);
    }
于 2013-02-01T11:16:36.897 回答
1

你试过FocusNavigationDirection.Previous(左)和FocusNavigationDirection.Next(右)吗?

与其他值相比,这可能会提供更可预测的行为。

于 2011-07-13T16:56:06.753 回答