将快捷键分配给WPF中的按钮

21 wpf c#-3.0

如何在WPF中为按钮指定快捷键?

谷歌搜索给了我答案,在标准的Winforms中追加_而不是'&'.

所以在我做完如下之后:

<Button Name="btnHelp" Content="_Help"></Button> 
Run Code Online (Sandbox Code Playgroud)

我没有发现'H'下划线.

这是第一个问题.

第二个问题是,如何在运行时按Alt + H后执行该操作.如果只是为了示例而显示一个消息框就足够了.

我正在使用C#,WPF

谢谢.

jhe*_*ger 44

这有点旧,但今天我遇到了同样的问题.
我发现最简单的解决方案是只使用AccessText元素作为按钮的内容.

<Button Command="{Binding SomeCommand}">
    <AccessText>_Help</AccessText>
</Button>
Run Code Online (Sandbox Code Playgroud)

Alt键时,按钮上的"H"将加下划线.
当您按下组合键Alt + H时,将执行绑定到该按钮的命令.

http://social.msdn.microsoft.com/Forums/vstudio/en-US/49c0e8e9-07ac-4371-b21c-3b30abf85e0b/button-hotkeys?forum=wpf

  • 派对有点晚了,但是`<Button Content ="_ Help"...... />`也可以解决问题. (12认同)
  • 究竟为什么人们应该总是随意在SO上做一点"暗示".我觉得你的解决方案很优雅.谢谢. (5认同)

yur*_*lav 39

使用自己的命令进行键绑定(+按钮绑定)的解决方案:

XAML文件的正文:

<Window.Resources>
    <RoutedUICommand x:Key="MyCommand1" Text="Text" />
    <RoutedUICommand x:Key="MyCommand2" Text="Another Text" />
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource MyCommand1}" 
                    Executed="FirstMethod" />
    <CommandBinding Command="{StaticResource MyCommand2}" 
                    Executed="SecondMethod" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Key="Z" Modifiers="Ctrl" Command="{StaticResource MyCommand1}" />
    <KeyBinding Key="H" Modifiers="Alt" Command="{StaticResource MyCommand2}" />
</Window.InputBindings>

<Grid>
    <Button x:Name="btn1" Command="{StaticResource MyCommand1}" Content="Click me" />
    <Button x:Name="btn2" Command="{StaticResource MyCommand2}" Content="Click me" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

和.CS文件:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    public void FirstMethod(Object sender, ExecutedRoutedEventArgs e)
    {
        // btn1
    }

    public void SecondMethod(Object sender, ExecutedRoutedEventArgs e)
    {
        // btn2
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢......但是...我不认为这可以在不必每次想要一个键盘快捷键的情况下在四个不同的地方编辑XAML时完成吗? (6认同)

Wal*_*mer 4

示例代码的快捷方式只是 h 。在

最初显示快捷方式下划线是 Windows 设置,不受应用程序控制。在 Windows XP 中,转到显示属性 -> 外观 -> 效果,您将看到一个标记为“隐藏键盘导航下划线字母,直到按下 Alt 键”的复选框。对于 Vista/Win7,我认为他们将该设置移到了其他地方。