【问题标题】:Custom command not working自定义命令不起作用
【发布时间】:2010-12-03 15:49:36
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    糟糕,抱歉,发布我的原始答案有点快。我现在看到问题不在于类型,而在于 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));
    

    【讨论】:

    • 我更新了我的帖子,请看看是否能解决您的问题。 :-)
    • XStatic 是多余的(至少从 .Net 4 开始)并且代码代码更改为 'Command="commands:MyApplicationCommands.MyCustomCommand"'
    • 也许吧,但我刚刚添加了 x:Static 并且添加控件引用的窗口中的错误消失了,控件现在呈现。 (commandconverter 无法从 system.string、.net 4 转换)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多