工具栏中的键盘快捷键

时间:2009-09-10 19:23:01

标签: wpf

我只用几个命令编写WPF应用程序,所以我使用的工具栏没有菜单。我想将ctrl-key快捷方式分配给工具栏上的按钮。有没有一种简单的方法可以做到这一点,而不必仅仅为了支持快捷方式而创建路由命令或ICommands?我宁愿在XAML中这样做,而不是代码隐藏。

3 个答案:

答案 0 :(得分:1)

你确实需要代码,一个事件告诉命令它是否可以被执行(通常不超过几行),另一个事件要做什么,所以每个绑定它的控件都做同样的事情。这是一个非常简单的例子:

XAML:

<UserControl x:Class="WPFTests.AppCommands"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <UserControl.CommandBindings>
        <CommandBinding Command="ApplicationCommands.New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
    </UserControl.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <CheckBox Grid.Row="0" Height="16" Name="checkBoxCanExecute" Margin="8" IsChecked="true">Can execute</CheckBox>
        <Button Grid.Row="1" Height="24" Padding="8,0,8,0" HorizontalAlignment="Left" Margin="8" Command="ApplicationCommands.New">ApplicationCommand.New</Button>
    </Grid>
</UserControl>

C#

使用System.Windows; 使用System.Windows.Controls; 使用System.Windows.Input;

namespace WPFTests
{
    /// <summary>
    /// Interaction logic for AppCommands.xaml
    /// </summary>
    public partial class AppCommands : UserControl
    {
        public AppCommands()
        {
            InitializeComponent();
        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = (bool)checkBoxCanExecute.IsChecked;
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("New executed");
        }
    }
}

编辑:根据RichardOD的要求。以下是我在评论中发布的更多信息:

<Button Command="ApplicationCommands.New">

这会将键盘手势Ctrl + N置于按钮上。如果你要做

<Button Command="ApplicationCommands.Open">

它会放置Ctrl + O.这在WPF的CommandBindings中隐式实现。您甚至可以使用自己的手势创建自己的命令。如果将命令绑定到菜单项,它将自动显示命令名旁边的手势,而不需要任何额外的efforr,只需:

<MenuItem Command="ApplicationCommands.New" />

这将在菜单项中显示[New Ctrl + N]。

答案 1 :(得分:0)

我得出的结论是,WPF没有提供一种向按钮添加Ctrl键的简单方法。我通过在代码隐藏中捕获按键,然后调用相应的ICommand解决了我的问题 - 相应按钮的Command属性绑定到的ICommand。这是一个丑陋的黑客,但它有效,而且在这种情况下它似乎是最好的方法。

答案 2 :(得分:0)

最简单和最简单的方法是自己添加键盘快捷键。当然,如果更改在Command中使用的快捷方式,则必须在工具提示中手动更改它。但也许我们可以将工具提示文本绑定到Command的属性以通过绑定获得快捷方式?有人知道是否可能吗?

        <Button Command="{Binding OpenDllCommand}" Content="Bla-bla >
            <Button.ToolTip>
                <StackPanel>
                    <TextBlock Text="F6" FontWeight="Bold" />
                    <TextBlock Text="Open MbUnit / MINT DLL with tests" />
                </StackPanel>
            </Button.ToolTip>
        </Button>