开发者

How to bind to Style target in a ContextMenu in Style?

开发者 https://www.devze.com 2023-01-07 09:24 出处:网络
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.

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开发者_JAVA技巧="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?


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}}"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消