如何在wpf中添加多个命令绑定

时间:2012-03-20 13:23:50

标签: c# wpf commandbinding

我正在使用WPF。我想为我的WPF应用程序创建键盘快捷键。我创建如下。 “ open ”的第一个命令绑定标记正在运行,退出的命令绑定不起作用。我不知道是什么原因。

<Window.CommandBindings>
<CommandBinding Command="Open" Executed="CommandBinding_Executed"/>
<CommandBinding Command="Exit" Executed="CommandBinding_Executed_1" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Open" Key="O" Modifiers="control" />
<KeyBinding Command="Exit" Key="E" Modifiers="control"/>
</Window.InputBindings>

以上代码收到以下错误:

无法将属性“Command”中的字符串“Exit”转换为类型的对象 'System.Windows.Input.ICommand'。 CommandConverter无法转换 System.String。对象'System.Windows.Input.CommandBinding'中的错误  标记文件'WpfApplication2; component / window1.xaml'第80行第25位。

1 个答案:

答案 0 :(得分:4)

你的问题是没有退出命令。你必须自己动手。

See here for built-in ApplicationCommands

创建自己的很容易,我使用静态实用程序类来保存我经常使用的常用命令。像这样:

public static class AppCommands
{
    private static RoutedUICommand exitCommand = new RoutedUICommand("Exit","Exit", typeof(AppCommands));

    public static RoutedCommand ExitCommand
    {
        get { return exitCommand; }
    }

    static AppCommands()
    {
        CommandBinding exitBinding = new CommandBinding(exitCommand);
        CommandManager.RegisterClassCommandBinding(typeof(AppCommands), exitBinding);
    }
}

然后你应该能够像这样绑定它:

<KeyBinding Command="{x:Static local:AppCommands.Exit}" Key="E" Modifiers="control"/>