一些输入绑定有效而另一些无效的原因是TextBox控件会捕捉并处理一些按键绑定。例如,它会处理粘贴的
CTRL+
V,将光标移到文本开头的
CTRL+
Home等。然而,其他一些按键组合如
CTRL+
F3则未被TextBox处理,因此这些按键将冒泡传递到上层。
如果你只是想禁用TextBox的输入绑定,那很简单-你可以使用命令来禁用默认行为。例如,在下面的例子中,使用
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>
希望这能有所帮助。