0
votes

I am working on a UserControl with some other controls inside. I want to set a keyboard shortcut (like Ctrl+Tab) to change the focus to the next control on the window, ignoring all the other controls that are inside the UserControl.

I'm trying to access the parent property like this:

FrameworkElement element = (FrameworkElement)this.Parent;

And then make a TraversalRequest from it, or something like this. I'm not sure what to do.

So, what is the correct way to move the focus to the next control on the screen, from the inside of the UserControl?

1

1 Answers

1
votes

There are several ways to do that. You could use the TraversalRequest class in a KeyDown or PreviewKeyDown event handler... from the linked page:

// Creating a FocusNavigationDirection object and setting it to a 
// local field that contains the direction selected.
FocusNavigationDirection focusDirection = _focusMoveValue;

// MoveFocus takes a TraveralReqest as its argument.
TraversalRequest request = new TraversalRequest(focusDirection);

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

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

Alternatively, you could just use the UIElement.Focus method in the handler:

particularControl.Focus();

Or even simpler... there's no need for any event handlers if you just set the Control.IsTabStop property on each control that you don't want the user to be able to focus to False:

<TextBox Name="NotTabStop" IsTabStop="False" ... />

Then the user will just be able to use the Tab key to move to the next control, as they'll be used to doing.