views:

9

answers:

1

I want to set the CommandTarget of the MenuItem of ContextMenu, in a Style, to the Style target, i.e., the control on which the style applies.

<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>

I Have tried RelativeSource TemplatedParent, Self, FindAncestor, none of them works. Is there any other way to select the target?

A: 

You are creating a single ContextMenu object that will be shared by many UI elements. The way to think about it is that you want to bind to the one that actually opened the ContextMenu. This is available on the PlacementTarget property of the ContextMenu. From the MenuItem, you can use a FindAncestor binding to get to the ContextMenu:

<MenuItem Command="{x:Static CCC}"
    CommandTarget="{Binding PlacementTarget,
        RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
Quartermeister
I tried this but didn't succeed. However I used a work around, just omit the commandtarget and set the focused control when context menu opening. Thanks you!
t.w