【问题标题】:How to create hotkey for button by modifying xaml?如何通过修改xaml为按钮创建热键?
【发布时间】:2014-09-07 08:07:06
【问题描述】:

我正在尝试通过一个简单的例子来学习 WPF 中的键绑定。

这是我的 XAML 文件:

<Window.Resources>
    <RoutedUICommand x:Key="myNewCommand"></RoutedUICommand>
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource myNewCommand}" Executed="Button_Click"></CommandBinding>
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Command="{Binding myNewCommand}" Key="B" />
</Window.InputBindings>

<Grid>
    <Button Command="{Binding myNewCommand}" Click="Button_Click"  Content="Click Here"/>

</Grid>

这是 Button_Click 的代码:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("hello");
    }

我点击按钮时收到“hello”消息,但按键盘上的“B”时没有响应。 我想在不更改 Button_click 的情况下进行此绑定,我可以仅在 XAML 中进行吗?怎么样?

【问题讨论】:

  • 我之前没用过 InputBindings,但是 myNewCommand 是一个StaticResource。你的InputBindings 命令应该是{StaticResource myNewCommand},就像在你的CommandBindings 中一样
  • 谢谢!它解决了问题。

标签: wpf xaml hotkeys keyboard-shortcuts


【解决方案1】:

您的命令绑定不正确。您应该将{Binding myNewCommand} 替换为{Binding Source={StaticResource myNewCommand}}。当您已经绑定了命令时,也不必在按钮上设置 Click 处理程序。

<Window.Resources>
    <RoutedUICommand x:Key="myNewCommand"/>
</Window.Resources>
<Window.CommandBindings>
    <CommandBinding Command="{StaticResource myNewCommand}"
                    Executed="MyCommandExecuted"/>
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Command="{Binding Source={StaticResource myNewCommand}}" Key="B" />
</Window.InputBindings>
<Grid>
    <Button Command="{Binding Source={StaticResource myNewCommand}}"
            Content="Click Here"/>
</Grid>

Executed 处理程序:

private void MyCommandExecuted(object sender, RoutedEventArgs e)
{
    MessageBox.Show("hello");
}

【讨论】:

    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多