I want to move to the next control when I press the Enter key instead of the Tab key in a WPF MVVM application. How can I achieve this?
Write This code in onstartup event of your application file
EventManager.RegisterClassHandler(GetType(TextBox), TextBox.KeyDownEvent, New RoutedEventHandler(AddressOf TextBox_KeyDown))
then define TextBox_KeyDown sub as
Private Sub TextBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs)
If e.Key = Key.Enter And TryCast(sender, TextBox).Tag <> "1" Then
' Creating a FocusNavigationDirection object and setting it to a
' local field that contains the direction selected.
Dim focusDirection As FocusNavigationDirection = FocusNavigationDirection.Next
' MoveFocus takes a TraveralReqest as its argument.
Dim request As New TraversalRequest(focusDirection)
' Gets the element with keyboard focus.
Dim elementWithFocus As UIElement = TryCast(Keyboard.FocusedElement, UIElement)
' Change keyboard focus.
If elementWithFocus IsNot Nothing Then
elementWithFocus.MoveFocus(request)
End If
End If
End Sub
I have used "tag" property of textbox for skip move focus. i.e. if some time you dont want to move to next control on enter key pressed (in the case of multiline text box where enter is required to create new line). Just set tag property to 1.