问题
I've got the following xaml:
<Window x:Class="Isolator.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Isolator" Height="394" Width="486" Background="Black" WindowStyle="None" WindowState="Maximized">
<Window.CommandBindings>
<CommandBinding Command="Close" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute"/>
</Window.CommandBindings>
<Window.ContextMenu>
<ContextMenu>
<MenuItem Header="Stop" Name="StopMenuItem" Click="StopMenuItem_Click" />
<MenuItem Header="Close" Command="Close"/>
</ContextMenu>
</Window.ContextMenu>
<Grid Loaded="Grid_Loaded">
</Grid>
</Window>
The Close menu items specifies that it should use the Close command. The Close command binding specifies that CommandBinding_CanExecute should be called for CanExecute, but CommandBinding_CanExecute never gets called. The close menu item is always disabled.
I assume that the binding isn't taking place. Can any one explain why?
If it has something to do with context menus not being in the visual tree, how do you get work around it?
回答1:
This statement Command="Close"
doesn't do anything. You are saying that the Command is the string "Close". This is why it doesn't work.
If the Close command instance is defined in the Window, use Command="{Binding Close}"
. Or if you are using the ApplicationCommands.Close, then it would be
Command="{x:Static ApplicationCommands.Close}"
来源:https://stackoverflow.com/questions/889234/cant-bind-command-from-menu-item-to-a-command-binding