在我的XAML中,我有以下内容:
<UserControl.CommandBindings>
<CommandBinding Command="Help"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
<MenuItem Header="Help" Command="Help" />
这很好。因此,当我单击上下文菜单时,将调用HelpExecuted()。
现在,我想再次执行相同的操作,只是使用自定义命令而不是“帮助”命令。所以我要做的是:
public RoutedCommand MyCustomCommand = new RoutedCommand();
并将我的XAML更改为:
<UserControl.CommandBindings>
<CommandBinding Command="MyCustomCommand"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
<MenuItem Header="Help" Command="MyCustomCommand" />
但是我收到错误消息:无法将属性“Command”中的字符串“MyCustomCommand”转换为类型“System.Windows.Input.ICommand”的对象。 CommandConverter无法从System.String转换。
我在这里想念什么?并且请注意,我想在XAML中完成所有操作,即不想使用CommandBindings.Add(new CommandBinding(MyCustomCommand ....
最佳答案
糟糕,抱歉,发布我的原始答案有点快。我现在看到问题不在于类型,而在于CommandBinding。您需要使用标记扩展名来解析命令名称。我通常将命令在其声明中设为静态,如下所示:
namespace MyApp.Commands
{
public class MyApplicationCommands
{
public static RoutedUICommand MyCustomCommand
= new RoutedUICommand("My custom command",
"MyCustomCommand",
typeof(MyApplicationCommands));
}
}
在XAML中:
<UserControl x:Class="..."
...
xmlns:commands="clr-namespace:MyApp.Commands">
...
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static commands:MyApplicationCommands.MyCustomCommand}"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
您需要使用xmlns引入包含类的 namespace 。在上面的示例中,我将其称为“命令”。
下面的原始帖子:
尝试将命令的类型更改为RoutedUICommand。构造函数有些不同:
public RoutedUICommand MyCustomCommand
= new RoutedUICommand("Description", "Name", typeof(ContainingClass));