Wpf 如何在样式中绑定到上下文菜单中的样式目标?

Wpf 如何在样式中绑定到上下文菜单中的样式目标?,wpf,binding,Wpf,Binding,我想将样式中ContextMenu菜单项的CommandTarget设置为样式目标,即应用样式的控件 <Style x:Key="AAA" TargetType="{x:Type BBB}"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem

我想将样式中ContextMenu菜单项的CommandTarget设置为样式目标,即应用样式的控件

<Style x:Key="AAA" TargetType="{x:Type BBB}">
        <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu>
                    <MenuItem Command="{x:Static CCC}" CommandTarget="{Binding ???}"/>
               </ContextMenu>
            </Setter.Value>
        </Setter>
  </Style>


我试过RelativeSourceTemplatedParent、Self、FindAncestor,它们都不起作用。是否有其他方法选择目标?

您正在创建一个由多个UI元素共享的ContextMenu对象。考虑这一点的方式是,您希望绑定到实际打开ContextMenu的菜单。这在ContextMenu的属性中可用。在MenuItem中,您可以使用FindAncestor绑定访问ContextMenu:

<MenuItem Command="{x:Static CCC}"
    CommandTarget="{Binding PlacementTarget,
        RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>

我尝试了这个,但没有成功。然而,我使用了一种变通方法,只需在上下文菜单打开时省略commandtarget并设置聚焦控件。谢谢你!