在我的 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 引入包含类的名称空间。在上面的示例中,我将其称为“命令”。
原帖如下:
尝试将命令类型更改为 RoutedUICommand。构造函数有点不同:
public RoutedUICommand MyCustomCommand
= new RoutedUICommand("Description", "Name", typeof(ContainingClass));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)