WPF FocusNavigationDirection,MoveFocus和Arrow键

时间:2011-04-19 15:50:26

标签: c# wpf keyboard focusmanager

我有一个简单的应用程序(一个带有6个按钮的网格 - 两行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 Documentation对于如何定义“左边”有点模糊。

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

2 个答案:

答案 0 :(得分:2)

为什么在使用“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);
    }

答案 1 :(得分:1)

您是否尝试过FocusNavigationDirection.Previous(左侧)和FocusNavigationDirection.Next(右侧)?

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