您正在尝试更改按钮的行为。最好为此使用代码。
最简单的方法是像这样将预览事件附加到窗口:
<Window
...
PreviewKeyDown="HandlePreviewKeyDown">
然后在代码中这样处理:
private void HandlePreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.IsRepeat)
{
e.Handled = true;
}
}
遗憾的是,这将禁用任何重复行为,即使在表单托管的文本框中也是如此。这是个有趣的问题。如果我找到一种更优雅的方法,我会添加到答案中。
编辑:
好的,有两种方法可以定义键绑定。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.InputBindings>
<KeyBinding x:Name="altD" Gesture="Alt+D" Command="{Binding ClickCommand}"/>
</Window.InputBindings>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Content="_Click" Command="{Binding ClickCommand}" />
<TextBox Grid.Row="1"/>
</Grid>
</Window>
上面的按钮会产生一次点击,因为您通过下划线隐含地请求了 Alt-C 手势:_Click 内容。然后窗口有一个与 Alt+D 的显式键绑定。
后面的代码现在应该适用于这两种情况,并且不应干扰常规重复:
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (e.IsRepeat)
{
if (((KeyGesture)altD.Gesture).Matches(this, e))
{
e.Handled = true;
}
else if (e.Key == Key.System)
{
string sysKey = e.SystemKey.ToString();
//We only care about a single character here: _{character}
if (sysKey.Length == 1 && AccessKeyManager.IsKeyRegistered(null, sysKey))
{
e.Handled = true;
}
}
}
}