0

I'm trying to implement a custom command for a right-click menu item to allow the application to reinitialize a specific state. Following Heinzi's guidance in How do I add a custom routed command in WPF?, I've added the necessary XAML/bindings.

<UserControl.Resources>
  <RoutedUICommand x:Key="UnsetCommand" Text="Reset" />
</UserControl.Resources>
<UserControl.CommandBindings>
  <CommandBinding Command="{StaticResource UnsetCommand}" Executed="UnsetExecuted" />
</UserControl.CommandBindings>

<ContextMenu>
  <MenuItem Command="{StaticResource UnsetCommand}" />
</ContextMenu>

And behind code

private void UnsetExecuted(object sender, ExecutedRoutedEventArgs e)
{
  FreeResources();

  Unset(false);
}

The issue I'm having is the menu item isn't enabled as expected.

Reset menu item isn't enabled

Thoughts on what I'm missing here?

EDIT: Fixed typo UnsetsCommand -> UnsetCommand

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ron O
  • 89
  • 7
  • What does your implementation of `UnsetCommand` look like? – Rachel Sep 05 '17 at 15:18
  • @Rachel It's the MenuItem visual tree thing. – 15ee8f99-57ff-4f92-890c-b56153 Sep 05 '17 at 15:18
  • 1
    Possible duplicate of [Why is this WPF RoutedCommand bound Context MenuItem disabled?](https://stackoverflow.com/questions/455551/why-is-this-wpf-routedcommand-bound-context-menuitem-disabled). The accepted answer there (put your command bindings in `ContextMenu.CommandBindings`) works, but there's another answer [which suggests binding `MenuItem.CommandTarget` to `ContextMenu.PlacementTarget`](https://stackoverflow.com/a/7381736/424129) -- and that solution works also. WPF MenuItems are out of the visual tree, which creates endless problems when it comes to binding. – 15ee8f99-57ff-4f92-890c-b56153 Sep 05 '17 at 15:19
  • I think it may just be a typo UnsetsCommand see the 's' at the end of Unset – kenny Sep 05 '17 at 16:00
  • @kenny The typo must have crept in when OP wrote the question, or else the text "Reset" wouldn't be appearing in the screenshot of the menu item. – 15ee8f99-57ff-4f92-890c-b56153 Sep 05 '17 at 16:34
  • @EdPlunkett good point. – kenny Sep 05 '17 at 17:12
  • Yes. It's a typo. Thanks for catching it. I haven't yet had a chance to get back to experiment with this solution, but it's probably the correction I needed. – Ron O Sep 05 '17 at 17:40
  • @EdPlunkett Thanks for the answer. I decided to go with the CommandTarget version. – Ron O Sep 05 '17 at 19:05

0 Answers0