写入文本框时触发键盘加速器

时间:2018-07-23 18:04:42

标签: c# xaml uwp

enter image description here

写入Button时按 D 会触发

点击事件Textbox

Textbox被聚焦时,如何抑制键盘加速器是一种优雅的方法吗?

XAML:

 <StackPanel Orientation="Vertical">
    <TextBox></TextBox>
    <Button Click="Button_Click" Content="Button with &quot;D&quot; 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)不能解决?

  • 我正在创建视频播放器,发现一键式快捷键是使用视频播放器进行快速操作(与VLC中相同)的巧妙解决方案。

迄今为止最好的解决方案: 创建自定义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>

1 个答案:

答案 0 :(得分:0)

我同意@Thomas Weller的评论,因为他不使用单个字母作为键盘加速器... 但是每个人都有自己的要求,无论如何,您都可以尝试e.handle = true当文本框集中显示事件时。

类似这样的东西:

public void Button_Click(object sender, ExecutedRoutedEventArgs e)
{
   if (textBox.isFocused)
   {
      e.handled = true;
   }
}