开发者

WPF FocusNavigationDirection, MoveFocus and Arrow keys

开发者 https://www.devze.com 2023-02-26 18:53 出处:网络
I have a simple application (a grid with 6 buttons - 2 rows of 3 - on it for testing) and am handling left and right arrow keys as follows

I have a simple application (a grid with 6 buttons - 2 rows of 3 - on it for testing) and am handling left and right arrow keys as follows

    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;
       开发者_StackOverflow     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);
        }

    }

Unfortunately, this doesn't behave as I expect as the focus always seems to move in the opposite direction to that specified by the FocusNavigationDirection.

Any thoughts on why this would be? The MSDN Documentation is a bit vague on how "to the left of" is defined.

In case it is needed, I have also defined the tab stops of each of the buttons as 1 through 6.


Why do you need to get the elementWithFocus while you can use "this" (window own scope)?

I modified your code a bit and it worked for me:

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


Have you tried FocusNavigationDirection.Previous (for left) and FocusNavigationDirection.Next (for right)?

That may give more predictable behavior than the other values.

0

精彩评论

暂无评论...
验证码 换一张
取 消