I suspect you haven't set CommandBinding for ApplicationCommands.Close
.
In case CommandBinding could not be found, command will always return false from CanExecute method. So, to enable command you have to:
- First, create CommandBinding at root element (may be at window) or at any parent element which needs to handle this command.
- Second, provide
CanExecute
handler in that command binding and sete.CanExecute
toTrue
in that handler based on condition where you want to enable this menuItem.
Small sample to achieve what i said above:
<TextBox>
<TextBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
Executed="CommandBinding_Executed"
CanExecute="CommandBinding_CanExecute"/>
</TextBox.CommandBindings>
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="E_xit" InputGestureText="Alt+F4"
Command="ApplicationCommands.Close"/>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
and in code behind handlers:
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
}
private void CommandBinding_CanExecute(object sender,
CanExecuteRoutedEventArgs e)
{
e.CanExecute = true; <-- Set this to true to enable bindings.
}
You can read more about it here - How to enable a Command and Commanding Overview.