WPF中ContextMenu(右键菜单)使用Command在部分控件上默认为灰色的处理方法

问题描述

今天发现如果我想在一个TextBlock弄一个右键菜单,并且使用Command绑定,结果发现默认菜单式不可用的.

问题原因

这个问题不知道算不算BUG,反正如果是在一个不可获得的焦点的东西上面使用ContextMenu,CanExecute的事件路由就会停止在ContextMenu,就没办法到达窗体上.一个解决的方案是吧CommandTarget设置到窗体上去.

事例代码

<Window x:Class="TestPopupMenuCommand.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="Close" Executed="CloseCommand"/>
        <CommandBinding Command="New"   Executed="NewCommand"/>
    </Window.CommandBindings>
    <Grid>
        <TextBlock>
            <TextBlock.ContextMenu>
                <ContextMenu>
                <MenuItem Command="New" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                <MenuItem Command="Close"/>
                </ContextMenu>
            </TextBlock.ContextMenu>
            test
        </TextBlock>
    </Grid>
</Window>

代码分析

里面的两个菜单项,New的是可用的,Close默认是不可以用的.因为我把New的CommandTarget修改了.

里面具体的command实现代码我就不贴了.

原文地址:https://www.cnblogs.com/atskyline/p/2555328.html