Wpf 如何在XAML中禁用上下文菜单中的所有菜单项?

Wpf 如何在XAML中禁用上下文菜单中的所有菜单项?,wpf,xaml,data-binding,contextmenu,Wpf,Xaml,Data Binding,Contextmenu,我尝试只绑定到ContextMenu.IsEnabled,但这使得它即使在单击关闭后,ContextMenu仍保持打开状态。在此简化代码和屏幕截图中进行了说明: <Window x:Class="ContextMenuSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com

我尝试只绑定到ContextMenu.IsEnabled,但这使得它即使在单击关闭后,ContextMenu仍保持打开状态。在此简化代码和屏幕截图中进行了说明:

<Window x:Class="ContextMenuSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="480"
        Width="640">
    <Grid>
        <Rectangle Width="100"
                   Height="100"
                   Fill="Black">
            <Rectangle.ContextMenu>
                <ContextMenu IsEnabled="False">
                    <MenuItem Header="Command _1" />
                    <MenuItem Header="Command _2" />
                    <MenuItem Header="Command _3" />
                    <MenuItem Header="Command _4" />
                </ContextMenu>
            </Rectangle.ContextMenu>
        </Rectangle>
    </Grid>
</Window>

有什么建议可以让我通过XAML以简单的方式禁用所有上下文菜单选项,而不会让上下文菜单显得很滑稽吗?


<ContextMenu>
    <ContextMenu.Resources>
        <Style TargetType="MenuItem">
            <Setter Property="IsEnabled" Value="False"/>
        </Style>
    </ContextMenu.Resources>
    <MenuItem Header="Command _1" />
    <MenuItem Header="Command _2" />
    <MenuItem Header="Command _3" />
    <MenuItem Header="Command _4" />
</ContextMenu>
应该这样做的话,重新启用就不那么有趣了,但您可以将setter中的值绑定到您可以轻松访问的对象上

此外,您还可以在更高级别禁用菜单:

<Rectangle Width="100"
           Height="100"
           Fill="Black"
           ContextMenuService.IsEnabled="False">
    <Rectangle.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Command _1" />
            <MenuItem Header="Command _2" />
            <MenuItem Header="Command _3" />
            <MenuItem Header="Command _4" />
        </ContextMenu>
    </Rectangle.ContextMenu>
</Rectangle>


然后它就不会打开了。

我会选择选项1获胜。我早该想到的!谢谢你!