自定义命令不工作 [英] Custom command not working
问题描述
在我的XAML我有这样的:
In my XAML I have this:
<UserControl.CommandBindings>
<CommandBinding Command="Help"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
<MenuItem Header="Help" Command="Help" />
这工作得很好。所以,当我点击右键菜单,HelpExecuted()被调用。
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();
和改变我的XAML为:
and change my XAML to:
<UserControl.CommandBindings>
<CommandBinding Command="MyCustomCommand"
CanExecute="HelpCanExecute"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
<MenuItem Header="Help" Command="MyCustomCommand" />
但我得到的错误:无法在属性字符串转换MyCustomCommand''命令',以类型的对象System.Windows.Input.ICommand。 CommandConverter不能从System.String转换。
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.
我在想什么吗?而且请注意,我想要做的这一切在XAML,即不希望使用CommandBindings.Add(新的CommandBinding(MyCustomCommand ....
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....
推荐答案
哎呀,不好意思,有点快后我原来的答复。我现在看到,这个问题是不是与类型,但用的CommandBinding。你需要使用一个标记扩展来解决命令名称。我通常让我的命令,静中有他们的声明是这样的:
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:
namespace MyApp.Commands
{
public class MyApplicationCommands
{
public static RoutedUICommand MyCustomCommand
= new RoutedUICommand("My custom command",
"MyCustomCommand",
typeof(MyApplicationCommands));
}
}
而在XAML:
And in the 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把包含类的命名空间。我把它叫做在我上面的例子'命令'。
You need to bring in the namespace of the containing class by using xmlns. I called it 'commands' in my example above.
下面的原帖:
尝试更改命令RoutedUICommand的类型。构造函数是一个有点不同:
Try changing the type of the command to RoutedUICommand. The constructor is a bit different:
public RoutedUICommand MyCustomCommand
= new RoutedUICommand("Description", "Name", typeof(ContainingClass));
这篇关于自定义命令不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!