views:

2621

answers:

2

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

+4  A: 

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);
}
gcores
A: 

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;
}
Mikko Rantanen
The above code did not work on my WPF window. The list ends up being empty. The first GetFocusedElement() call above returns null. I agree this code exactly matches the documentation, but unfortunately it didn't work for me. I'm digging to figure out why.
Michael Hewitt
Where do you call the code? Note that the window must be active so constructor is definitely out. OnLoad might work, I used Activated which is called each time you activate the window.
Mikko Rantanen