自定义命令不起作用
在我的 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...)
In my XAML I have this:
<UserControl.CommandBindings>
<CommandBinding Command="Help"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
<MenuItem Header="Help" Command="Help" />
This works fine. So when I click the context menu, HelpExecuted() gets called.
Now I want to do the same again except use a custom command instead of the Help command. So what I do is:
public RoutedCommand MyCustomCommand = new RoutedCommand();
and change my XAML to:
<UserControl.CommandBindings>
<CommandBinding Command="MyCustomCommand"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
<MenuItem Header="Help" Command="MyCustomCommand" />
But i get the error: Cannot convert string 'MyCustomCommand' in attribute 'Command' to object of type 'System.Windows.Input.ICommand'. CommandConverter cannot convert from System.String.
What am I missing here? And please note that I want to do it all in XAML, i.e. don't want to use CommandBindings.Add(new CommandBinding(MyCustomCommand....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
哎呀,抱歉,发布我原来的答案有点快。我现在发现问题不在于类型,而在于 CommandBinding。您需要使用标记扩展来解析命令名称。我通常在其声明中将命令设置为静态,如下所示:
在 XAML 中:
您需要使用 xmlns 引入包含类的命名空间。在上面的示例中,我将其称为“命令”。
原始帖子如下:
尝试将命令类型更改为 RoutedUICommand。构造函数有点不同:
Oops, sorry, was a bit fast to post my original answer. I now see that the problem is not with the type but with the CommandBinding. You need to use a markup extension to resolve the command name. I usually make my commands static in their declaration like this:
And in the XAML:
You need to bring in the namespace of the containing class by using xmlns. I called it 'commands' in my example above.
Original post below:
Try changing the type of the command to RoutedUICommand. The constructor is a bit different: