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

前端 未结 5 459
野的像风
野的像风 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:33

    In addition to Adi Lester his (very helpful) answer I would like to suggest some improvements/extensions that helped me with my implementation.

    Gesture.Matches

    The foundBinding can also be done by calling Gesture.Matches. Change the foundBinding Linq query to the following:

    KeyBinding foundBinding = ((UIElement)this).InputBindings
                .OfType()
                .FirstOrDefault(inputBinding => inputBinding.Gesture.Matches(sender, eventArgs));
    

    MouseBinding

    Furthermore you can also define MouseBindings.

    
    

    You then also need to subscribe to PreviewMouseEvents e.g. PreviewMouseUp and PreviewMouseDoubleClick. The implementation is then almost the same as for KeyBindings.

    private void OnTextBoxPreviewMouseUp(object sender, MouseButtonEventArgs eventArgs)
    {
        MouseBinding foundBinding = ((UIElement)this).InputBindings
            .OfType()
            .FirstOrDefault(inputBinding => inputBinding.Gesture.Matches(sender, eventArgs));
    
        if (foundBinding != null)
        {
            eventArgs.Handled = true;
            if (foundBinding.Command.CanExecute(foundBinding.CommandParameter))
            {
                foundBinding.Command.Execute(foundBinding.CommandParameter);
            }
        }
    }
    

提交回复
热议问题