How to programmatically navigate WPF UI element tab stops?

a 夏天 提交于 2019-12-17 16:28:42

问题


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 element, visit the next tab stop, sniff the corresponding element, and so on until I reach the last tab stop.

Thanks, - Mike


回答1:


You do that using MoveFocus as shown in this MSDN article which explains everything about focus: Focus Overview.

Here is some sample code to get to the next focused element (got it from that article, slightly modified).

// MoveFocus takes a TraversalRequest as its argument.
TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);

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

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



回答2:


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<IInputElement> elements = new List<IInputElement>();

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


来源:https://stackoverflow.com/questions/809382/how-to-programmatically-navigate-wpf-ui-element-tab-stops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!