Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - WPF FocusNavigationDirection, MoveFocus and Arrow keys

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...