How to programmatically navigate WPF UI element tab stops?
Asked Answered
P

2

11

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

Physique answered 30/4, 2009 at 22:18 Comment(0)
C
30

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);
}
Cheep answered 30/4, 2009 at 22:41 Comment(0)
U
1

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;
}
Understrapper answered 30/4, 2009 at 22:48 Comment(2)
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.Physique
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.Understrapper

© 2022 - 2024 — McMap. All rights reserved.