0

I want to have custom Commands to respond to in my application. So I was following the instructions on this answer, and created a static class for my commands:

namespace MyNamespace {
    public static class Commands {
        public static readonly RoutedUICommand Create = new RoutedUICommand(
            "Create Thing", nameof(Create),
            typeof(MyControl)
        );
    }
}

I then tried using it on my UserControl:

<UserControl x:Class="MyNamespace.MyControl"

             ...boilerplate...

             xmlns:local="clr-namespace:MyNamespace">
    <UserControl.CommandBindings>
        <CommandBinding Command="local:Commands.Create"
                        CanExecute="CanCreateThing"
                        Executed="CreateThing"/>
    </UserControl.CommandBindings>

    ...the control's contents...
</UserControl>

The method CanCreateThing always sets CanExecute to true. CreateThing currently does nothing.

I get this error on the usage of MyControl in the window XAML:

Type reference cannot find type named '{clr-namespace:MyNamespace;assembly=MyAssembly}Commands'.

And this one in the Command="..." attribute in the binding.

Invalid value for property 'Command': 'Microsoft.VisualStudio.DesignTools.Xaml.LanguageService.Semantics.XmlValue'

UPDATE

Mathew got rid of the errors, however, the menu items with those commands are still grayed out. Relevant code:

<TreeView ...>
    <ContextMenu>
        <MenuItem Command="{x:Static local:Commands.Create}"/>
    </ContextMenu>
    ...
</TreeView>

MyControl.xaml.cs

//...
private void CanCreateThing(object sender, CanExecuteRoutedEventArgs e) {
    e.CanExecute = true;
}
//...
Community
  • 1
  • 1

1 Answers1

0

With Mathew's help, a fix was found:

First, I had to replace all instances of local:Commands.Create with {x:Static local:Commands.Create}. However, the menu items would still be gray.

So in each menu item, I added a CommandTarget referencing the ancestor ContextMenu:

<MenuItem Command="{x:Static local:Commands.CreateTrigger}"
                    CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>

And that made the menu items clickable.

Community
  • 1
  • 1