自定义命令无法使用。

12

我的XAML代码如下:

<UserControl.CommandBindings>
    <CommandBinding Command="Help"
   CanExecute="HelpCanExecute"
   Executed="HelpExecuted" />
</UserControl.CommandBindings>

<MenuItem Header="Help" Command="Help" />

这个很好用。因此,当我点击上下文菜单时,HelpExecuted() 会被调用。

现在我想再次执行相同的操作,但是使用自定义命令而不是 Help 命令。所以我的做法是:

public RoutedCommand MyCustomCommand = new RoutedCommand();

并将我的XAML更改为:

<UserControl.CommandBindings>
    <CommandBinding Command="MyCustomCommand"
   CanExecute="HelpCanExecute"
   Executed="HelpExecuted" />
</UserControl.CommandBindings>

<MenuItem Header="Help" Command="MyCustomCommand" />

但是我遇到了错误:无法将字符串'MyCustomCommand'转换为类型'System.Windows.Input.ICommand'的对象属性'Command'。 CommandConverter无法从System.String进行转换。

我在这里缺少什么?请注意,我想要全部在XAML中完成,即不想使用CommandBindings.Add(new CommandBinding(MyCustomCommand....

1个回答

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引入包含类的命名空间。在上面的示例中,我将其称为“commands”。 以下是原始帖子: 尝试将命令的类型更改为RoutedUICommand。构造函数有点不同:
public RoutedUICommand MyCustomCommand 
             = new RoutedUICommand("Description", "Name", typeof(ContainingClass));

我更新了我的帖子,请看看是否解决了你的问题。 :-) - René
1
XStatic已经过时了(至少在.Net 4中),代码可以更改为“Command =” commands:MyApplicationCommands.MyCustomCommand“”。 - ΩmegaMan
也许吧,但我刚刚添加了x:Static,窗口中添加控件引用的错误消失了,现在控件可以渲染了。(commandconverter无法从system.string,.net 4进行转换) - CRice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接