Custom command not working

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....

Answers


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));
    }
}

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>

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:

public RoutedUICommand MyCustomCommand 
             = new RoutedUICommand("Description", "Name", typeof(ContainingClass));

Need Your Help

find/trace element in a sorted array

javascript arrays sorting search

Let's say there is an array like var arr = [{id:'anId', value: 'aValue'}, ......] and a custom sorting by value is done to it: