【问题标题】:how to add multiple command bindings in wpf如何在 wpf 中添加多个命令绑定
【发布时间】:2012-06-28 20:34:34
【问题描述】:

我正在使用 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>

上面的代码出现以下错误:

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

【问题讨论】:

  • 能否提供实际代码和xaml?

标签: c# wpf commandbinding


【解决方案1】:

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

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"/>

【讨论】:

  • @havan:嗯,.NET 中已经内置了几组命令。有一组 ComponentCommands、MediaCommands、NavigationCommands 和 EditingCommands。但是创建自己的命令很容易。我已经编辑了我的答案以显示一种方法。另外,我不知道为什么微软忽略了在 ApplicationCommands 中添加 ExitCommand。
猜你喜欢
  • 2012-11-30
  • 2016-05-07
  • 2010-10-10
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多