KeyBinding in UserControl doesn't work when TextBox has the focus

前端 未结 5 464
野的像风
野的像风 2020-11-27 17:28

The following situation. I\'ve got a UserControl with five keybindings. When the TextBox has the focus the keybindings of the UserControl stop firing..

Is there a wa

5条回答
  •  再見小時候
    2020-11-27 17:36

    This Thread is old but many have this problem. My research has shown, that Adi Lester's Solution ist the only one which isn't a "dirty" Workaround. For anayone who needs, the VisualBasic.NET Implemantation:

    Public Class InputBindingsBehavior
        Public Shared ReadOnly TakesInputBindingPrecedenceProperty As DependencyProperty = DependencyProperty.RegisterAttached("TakesInputBindingPrecedence", GetType(Boolean), GetType(InputBindingsBehavior), New UIPropertyMetadata(False, AddressOf OnTakesInputBindingPrecedenceChanged))
    
        Public Shared Function GetTakesInputBindingPrecedence(obj As UIElement) As Boolean
            Return obj.GetValue(TakesInputBindingPrecedenceProperty)
        End Function
    
        Public Shared Sub SetTakesInputBindingPrecedence(obj As UIElement, value As Boolean)
            obj.SetValue(TakesInputBindingPrecedenceProperty, value)
        End Sub
    
        Public Shared Sub OnTakesInputBindingPrecedenceChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
            AddHandler DirectCast(d, UIElement).PreviewKeyDown, AddressOf InputBindingsBehavior_PreviewKeyDown
        End Sub
    
        Public Shared Sub InputBindingsBehavior_PreviewKeyDown(sender As Object, e As KeyEventArgs)
            Dim uielement = DirectCast(sender, UIElement)
    
            Dim foundBinding = uielement.InputBindings.OfType(Of KeyBinding).FirstOrDefault(Function(kb As KeyBinding) kb.Key = e.Key And kb.Modifiers = e.KeyboardDevice.Modifiers)
    
            If foundBinding IsNot Nothing Then
                e.Handled = True
                If foundBinding.Command.CanExecute(foundBinding.CommandParameter) Then
                    foundBinding.Command.Execute(foundBinding.CommandParameter)
                End If
            End If
        End Sub
    
    End Class
    
    

    The rest as mentioned.

提交回复
热议问题