I saw this SO question but when I tried it it does not work.
I know I can do mvvm but what the execute command be doing is view specific so I wanted it to be done on the view.
<Grid>
<TextBox>
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="_Copy" CommandTarget="{Binding Path=PlacementTarget,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}">
<MenuItem.CommandBindings>
<CommandBinding CanExecute="CommandBinding_CanExecute"
Executed="CommandBinding_Executed"
/>
</MenuItem.CommandBindings>
</MenuItem>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>
Code behind:
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
}
I am expecting the menu to be disabled but it is not:
I tried other approaches:
<!--Approach 2: CopyCommand as property of the Window. CopyCommand is in code-behind of the window-->
<MenuItem Header="_Copy" Command="{Binding Path=CopyCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
<!--Approach 3: Saw other samples on the net about binding to PlacementTarget. CopyCommand is in code-behind of the window-->
<MenuItem Header="_Copy" Command="{Binding Path=PlacementTarget.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>