自定义命令不起作用

时间:2010-12-03 15:49:36

标签: c# .net wpf vb.net xaml

在我的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 ....)

1 个答案:

答案 0 :(得分:15)

哎呀,抱歉,发布我的原始答案有点快。我现在看到问题不在于类型,而在于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引入包含类的命名空间。我在上面的例子中称它为“命令”。

以下原帖:

尝试将命令类型更改为RoutedUICommand。构造函数有点不同:

public RoutedUICommand MyCustomCommand 
             = new RoutedUICommand("Description", "Name", typeof(ContainingClass));
相关问题