Button
时按 D 会触发点击事件Textbox
。
在Textbox
被聚焦时,如何抑制键盘加速器是一种优雅的方法吗?
XAML:
<StackPanel Orientation="Vertical">
<TextBox></TextBox>
<Button Click="Button_Click" Content="Button with "D" as keyboard accelerator" Margin="0,10">
<Button.KeyboardAccelerators>
<KeyboardAccelerator Key="D"></KeyboardAccelerator>
</Button.KeyboardAccelerators>
</Button>
<TextBlock x:Name="ButtonClickCounter"></TextBlock>
</StackPanel>
C#:
int buttonClickCounter;
private void Button_Click(object sender, RoutedEventArgs e)
{
ButtonClickCounter.Text = $"Button clicked {++buttonClickCounter} times";
}
编辑:
为什么带修饰符的加速器(Alt + D或Ctrl + D)不能解决?
迄今为止最好的解决方案:
创建自定义KeyboardAccelerator
,以检查焦点是否设置为文本框。只有将需要完成的代码编辑才能将KeyboardAccelerator
更改为AcceleratorWithHandledActionIfTextboxIsFocused
。
public class AcceleratorWithHandleDActionIfTextboxIsFocused:KeyboardAccelerator
{
public AcceleratorWithHandleActionIfTextboxIsFocused()
{
Invoked += AcceleratorWithHandleActionIfTextboxIsFocused_Invoked;
}
private void AcceleratorWithHandleActionIfTextboxIsFocused_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
{
var focusedElement = FocusManager.GetFocusedElement();
if (focusedElement.GetType() == typeof(TextBox))
args.Handled = true;
}
}
XAML的一部分:
<Button.KeyboardAccelerators>
<custom:AcceleratorWithHandleDActionIfTextboxIsFocused Key="D"></KeyboardAccelerator>
</Button.KeyboardAccelerators>
答案 0 :(得分:0)
我同意@Thomas Weller的评论,因为他不使用单个字母作为键盘加速器... 但是每个人都有自己的要求,无论如何,您都可以尝试e.handle = true当文本框集中显示事件时。
类似这样的东西:
public void Button_Click(object sender, ExecutedRoutedEventArgs e)
{
if (textBox.isFocused)
{
e.handled = true;
}
}