Moving to next control on Enter keypress in WPF

前端 未结 7 2078
梦毁少年i
梦毁少年i 2020-11-30 23:20

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?

7条回答
  •  悲哀的现实
    2020-11-30 23:40

    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.

提交回复
热议问题