robertwojnar
robertwojnar

Reputation: 129

How to get PlacementTarget.Content in ContextMenu?

I have a situation, where I have to get Content from ContextMenu's Button. Something like this:

<Button Content="Test" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.Content}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

But.. that doesn't work. The problem can be easily solved with the button's Tag, but the Tag is in use already:

<Button Content="Test" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75"
        Tag="{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=2}}">
    <Button.ContextMenu>
        <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
            <MenuItem Header="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.Content}"/>
            <MenuItem Header="Option 2" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>

I'm using Tag to get main DataContext. Yet I still need the content of the button.

Why getting "Tag" from Placement target works, but "Content" does not?

How can I get it?

Upvotes: 1

Views: 784

Answers (1)

ASh
ASh

Reputation: 35680

MenuItem doesn't have "PlacementTarget" property, bidning to Self doesn't work. There should be "System.Windows.Data Error: 40 : BindingExpression path error: 'PlacementTarget' property not found on 'object' 'MenuItem'" warning in Output.

Change the path:

<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
    <MenuItem Header="{Binding Path=Parent.PlacementTarget.Content, RelativeSource={RelativeSource Self}}"/>
    <MenuItem Header="Option 2" />
</ContextMenu>

or RelativeSource:

<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
    <MenuItem Header="{Binding Path=PlacementTarget.Content, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
    <MenuItem Header="Option 2" />
</ContextMenu>

Upvotes: 2

Related Questions