commandbinding not working?

2019-01-20 04:28发布

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

标签: wpf command
2条回答
放我归山
2楼-- · 2019-01-20 04:45

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

查看更多
▲ chillily
3楼-- · 2019-01-20 04:48

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?!
查看更多
登录 后发表回答