Can't bind command from Menu Item to a Command Binding

淺唱寂寞╮ 提交于 2019-12-10 11:58:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!