If you only want it to work for a few text boxes, Jay's answer is best.
If you want your whole application to work that way, makwana.a's answer is better but can be improved.
Below is my modification of makwana.a's answer, which I have used in numerous applications. It also includes support for moving to the next control via enter if the active control is a check box. Instead of using the tag property to decide whether or not the focus should move, I used the AcceptsReturn
property of the text box. I did this because it defaults to false and will only be set to true on multi-line text boxes. In that case, you won't want the focus to move to the next control on enter anyway.
Declare these event handlers in the OnStartup void of App.xaml
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.KeyDownEvent, new KeyEventHandler(TextBox_KeyDown));
EventManager.RegisterClassHandler(typeof(CheckBox), CheckBox.KeyDownEvent, new KeyEventHandler(CheckBox_KeyDown));
Here are the rest of the methods needed to make it work application wide.
void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter & (sender as TextBox).AcceptsReturn == false) MoveToNextUIElement(e);
}
void CheckBox_KeyDown(object sender, KeyEventArgs e)
{
MoveToNextUIElement(e);
//Sucessfully moved on and marked key as handled.
//Toggle check box since the key was handled and
//the checkbox will never receive it.
if (e.Handled == true)
{
CheckBox cb = (CheckBox)sender;
cb.IsChecked = !cb.IsChecked;
}
}
void MoveToNextUIElement(KeyEventArgs e)
{
// Creating a FocusNavigationDirection object and setting it to a
// local field that contains the direction selected.
FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;
// 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)
{
if (elementWithFocus.MoveFocus(request)) e.Handled = true;
}
}
Edit
I updated the code to mark the keystroke as handled if the movement was successful and also toggle the checkbox since the key was handled and will no longer reach it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…