Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically navigate WPF UI element tab stops?

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

like image 484
Michael Hewitt Avatar asked Apr 30 '09 22:04

Michael Hewitt


2 Answers

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);
}
like image 165
gcores Avatar answered Nov 19 '22 23:11

gcores


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;
}
like image 1
Mikko Rantanen Avatar answered Nov 20 '22 00:11

Mikko Rantanen