4

I working on a multi-tab application (For Ex: Multi-Tab Text Editor), where each tabitem has its own content. And in contextmenu of tabitem, their is menuitem with a command, say SelectAll command.

After running app, the menu item is always disabled, no command execution is done.

So, how can i make my commandbindings work ?

CODE ::

In Context Menu At TextEditor>

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

In CommandBindings At TextEditor>

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

The TabItems with TextEditor are created at run time

biju
  • 17,554
  • 10
  • 59
  • 95
Code0987
  • 2,598
  • 3
  • 33
  • 51

2 Answers2

4

This happens since the ContextMenus are separate windows with their own VisualTree and LogicalTree.

Use like this

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

For more check the link below

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

biju
  • 17,554
  • 10
  • 59
  • 95
  • This works great. But the XAML editor displays a spurious "Object reference not set to an instance of an object". It works fine once compiled and run, but it'd be nice to not have the error displayed in the editor. Any way to fix that? – Peter Duniho Mar 14 '16 at 03:01
1

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

and if you have any binding problems in future, take a look at Snoop. its an easy to use tool to check your bindings at runtime.

i always check 2 things:

  • is my DataContext the one i expect?!
  • is my Binding Path the one i want?!
blindmeis
  • 22,175
  • 7
  • 55
  • 74