Command not working?

I am working on a multi-tasking application (for Ex: a multi-page text editor) where each tabitem has its own content. And in the tabitem context menu, they are menuitem with a command, for example, the SelectAll command.

After starting the application, the menu item is always disabled, the command is not executed.

So how can I make my teams work?

CODE::

In the context menu in TextEditor>

<MenuItem Command="local:TextEditor.SelectAllCommand" Header="Select All" /> 

In CommandBindings in TextEditor>

 <UserControl.CommandBindings> <CommandBinding Command="local:TextEditor.SelectAllCommand" Executed="SelectAll_Executed" CanExecute="SelectAll_CanExecute" /> </UserControl.CommandBindings> 

TabItems with TextEditor are created at runtime

+2
source share
2 answers

This is because ContextMenus are separate windows with their own VisualTree and LogicalTree.

Use it as

 <MenuItem Header="Cut" Command="Cut" CommandTarget=" {Binding Path=PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/> 

For more details see the link below.

http://www.wpftutorial.net/RoutedCommandsInContextMenu.html

+3
source

see biju answer, your DataContext for your ContextMenu is not the one you expect.

and if you have problems with binding in the future, check out Snoop . Its an easy-to-use tool for checking bindings at runtime.

I always check 2 things:

  • is this my DataContext that I expect ?!
  • My binding path is the one I want ?!
+1
source

All Articles