How to programmatically navigate WPF UI element tab stops?

前端 未结 2 834
温柔的废话
温柔的废话 2020-12-06 06:16

Can anyone tell me how to programmatically navigate through all UI element tab stops in a WPF application? I want to start with the first tab stop sniff the corresponding e

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 07:19

    You can do this with the MoveFocus call. You can get the currently focused item through the FocusManager. The following code will iterate all objects in the window and add them to a list. Note that this will physically modify the window by switching the focus. Most likely the code will not work if the window is not active.

    // Select the first element in the window
    this.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
    
    TraversalRequest next = new TraversalRequest(FocusNavigationDirection.Next);
    List elements = new List();
    
    // Get the current element.
    UIElement currentElement = FocusManager.GetFocusedElement(this) as UIElement;
    while (currentElement != null)
    {
        elements.Add(currentElement);
    
        // Get the next element.
        currentElement.MoveFocus(next);
        currentElement = FocusManager.GetFocusedElement(this) as UIElement;
    
        // If we looped (If that is possible), exit.
        if (elements[0] == currentElement)
            break;
    }
    

提交回复
热议问题