当TextBox具有焦点时,UserControl中的KeyBinding不起作用

时间:2012-10-17 19:17:01

标签: wpf xaml mvvm focus inputbinding

以下情况。我有一个带有五个键绑定的UserControl。当TextBox具有焦点时,UserControl的键绑定将停止触发..

有没有办法解决这个'问题'?

<UserControl.InputBindings>
    <KeyBinding Key="PageDown" Modifiers="Control" Command="{Binding NextCommand}"></KeyBinding>
    <KeyBinding Key="PageUp" Modifiers="Control" Command="{Binding PreviousCommand}"></KeyBinding>
    <KeyBinding Key="End" Modifiers="Control"  Command="{Binding LastCommand}"></KeyBinding>
    <KeyBinding Key="Home" Modifiers="Control" Command="{Binding FirstCommand}"></KeyBinding>
    <KeyBinding Key="F" Modifiers="Control" Command="{Binding SetFocusCommand}"></KeyBinding>
</UserControl.InputBindings>
<TextBox Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Gesture="Enter" Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl }}, Path=DataContext.FilterCommand}"></KeyBinding>
    </TextBox.InputBindings>
</TextBox>

似乎功能键( F1 等)和 ALT + [key] 可以正常工作。我认为 CTRL SHIFT 修饰符以某种方式“阻止”事件冒泡到UserControl。

5 个答案:

答案 0 :(得分:44)

某些输入绑定有效的原因,有些则不是TextBox控件捕获并处理某些键绑定。例如,它处理 CTRL + V 用于粘贴, CTRL + Home 用于转到文本的开头另一方面,其他组合键如 CTRL + F3 不会被TextBox处理,因此它们会冒出来。

如果您只想禁用TextBox的输入绑定,那很简单 - 您可以使用ApplicationCommands.NotACommand命令来禁用默认行为。例如,在以下情况中,将禁用使用 CTRL + V 进行粘贴:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="V" Modifiers="Control" Command="ApplicationCommands.NotACommand" />
    </TextBox.InputBindings>
</TextBox>

然而,让它冒泡到用户控件有点棘手。我的建议是创建一个附加行为,该行为将应用于UserControl,注册到其PreviewKeyDown事件,并在它们到达TextBox之前根据需要执行其输入绑定。执行输入绑定时,这将优先于UserControl。

我写了一个基本行为来实现此功能,以帮助您入门:

public class InputBindingsBehavior
{
    public static readonly DependencyProperty TakesInputBindingPrecedenceProperty =
        DependencyProperty.RegisterAttached("TakesInputBindingPrecedence", typeof(bool), typeof(InputBindingsBehavior), new UIPropertyMetadata(false, OnTakesInputBindingPrecedenceChanged));

    public static bool GetTakesInputBindingPrecedence(UIElement obj)
    {
        return (bool)obj.GetValue(TakesInputBindingPrecedenceProperty);
    }

    public static void SetTakesInputBindingPrecedence(UIElement obj, bool value)
    {
        obj.SetValue(TakesInputBindingPrecedenceProperty, value);
    }

    private static void OnTakesInputBindingPrecedenceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((UIElement)d).PreviewKeyDown += new KeyEventHandler(InputBindingsBehavior_PreviewKeyDown);
    }

    private static void InputBindingsBehavior_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        var uielement = (UIElement)sender;

        var foundBinding = uielement.InputBindings
            .OfType<KeyBinding>()
            .FirstOrDefault(kb => kb.Key == e.Key && kb.Modifiers == e.KeyboardDevice.Modifiers);

        if (foundBinding != null)
        {
            e.Handled = true;
            if (foundBinding.Command.CanExecute(foundBinding.CommandParameter))
            {
                foundBinding.Command.Execute(foundBinding.CommandParameter);
            }
        }
    }
}

用法:

<UserControl local:InputBindingsBehavior.TakesInputBindingPrecedence="True">
    <UserControl.InputBindings>
        <KeyBinding Key="Home" Modifiers="Control" Command="{Binding MyCommand}" />
    </UserControl.InputBindings>
    <TextBox ... />
</UserControl>

希望这有帮助。

答案 1 :(得分:4)

Adi Lester的解决方案效果很好。这是使用Behavior的类似解决方案。 C#代码:

public class AcceptKeyBinding : Behavior<UIElement>
{


    private TextBox _textBox;



    /// <summary>
    ///  Subscribes to the PreviewKeyDown event of the <see cref="TextBox"/>.
    /// </summary>
    protected override void OnAttached()
    {
        base.OnAttached();

        _textBox = AssociatedObject as TextBox;

        if (_textBox == null)
        {
            return;
        }

        _textBox.PreviewKeyDown += TextBoxOnPreviewKeyDown;
    }

    private void TextBoxOnPreviewKeyDown(object sender, KeyEventArgs keyEventArgs)
    {
        var uielement = (UIElement)sender;

        var foundBinding = uielement.InputBindings
            .OfType<KeyBinding>()
            .FirstOrDefault(kb => kb.Key == keyEventArgs.Key && kb.Modifiers ==           keyEventArgs.KeyboardDevice.Modifiers);

        if (foundBinding != null)
        {
            keyEventArgs.Handled = true;
            if (foundBinding.Command.CanExecute(foundBinding.CommandParameter))
            {
                foundBinding.Command.Execute(foundBinding.CommandParameter);
            }
        }
    }

    /// <summary>
    ///     Unsubscribes to the PreviewKeyDown event of the <see cref="TextBox"/>.
    /// </summary>
    protected override void OnDetaching()
    {
        if (_textBox == null)
        {
            return;
        }

        _textBox.PreviewKeyDown -= TextBoxOnPreviewKeyDown;

        base.OnDetaching();
    }

}

和XAML:

<TextBox>
  <TextBox.InputBindings>
      <KeyBinding Key="Enter" Modifiers="Shift" Command="{Binding CommandManager[ExecuteCommand]}"
          CommandParameter="{Binding ExecuteText}" />
  </TextBox.InputBindings>
      <i:Interaction.Behaviors>
         <behaviours:AcceptKeyBinding />
      </i:Interaction.Behaviors>
</TextBox>

答案 2 :(得分:1)

除了Adi Lester他(非常有帮助)的回答,我想建议一些改进/扩展,帮助我实施。

<强> Gesture.Matches

也可以通过调用Gesture.Matches来完成foundBinding。将foundBinding Linq查询更改为以下内容:

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

<强> MouseBinding

此外,您还可以定义MouseBindings。

<MouseBinding Command="{Binding DataContext.AddInputValueCommand, ElementName=root}" CommandParameter="{Binding}" Gesture="Shift+MiddleClick" />

然后您还需要订阅PreviewMouseEvents,例如PreviewMouseUp和PreviewMouseDoubleClick。然后,实现几乎与KeyBindings相同。

private void OnTextBoxPreviewMouseUp(object sender, MouseButtonEventArgs eventArgs)
{
    MouseBinding foundBinding = ((UIElement)this).InputBindings
        .OfType<MouseBinding>()
        .FirstOrDefault(inputBinding => inputBinding.Gesture.Matches(sender, eventArgs));

    if (foundBinding != null)
    {
        eventArgs.Handled = true;
        if (foundBinding.Command.CanExecute(foundBinding.CommandParameter))
        {
            foundBinding.Command.Execute(foundBinding.CommandParameter);
        }
    }
}

答案 3 :(得分:1)

此线程较旧,但许多存在此问题。我的研究表明,Adi Lester的解决方案是唯一一种并非“肮脏”的解决方法。 对于需要的Anayone,VisualBasic.NET的要求:

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

其余提到。

答案 4 :(得分:0)

<UserControl.Style>
    <Style TargetType="UserControl">
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="FocusManager.FocusedElement" Value="   {Binding ElementName=keyPressPlaceHoler}" />
                </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Style>

keyPressPlaceHoler是目标uielement

的容器名称

记得在usercontrol中设置Focusable="True"