CommandParameters in ContextMenu in WPF

The problem is that the ContextMenu is at the root of its own visual tree, so any RelativeSource.FindAncestor bindings won’t go past the ContextMenu.

One solution is to use the PlacementTarget property to set up a two-stage binding from your Label:

<Label Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={
    x:Type TreeView}}}">
    <Label.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" Command="{x:Static local:Commands.DeleteCommand}"
                CommandParameter="{Binding PlacementTarget.Tag, RelativeSource={
                RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>
        </ContextMenu>
    </Label.ContextMenu>
</Label>

This is quite hacky, however. You’re better off setting the CommandTarget property of your MenuItem to the ContextMenu’s PlacementTarget and having the command handler on your TreeView. This means you won’t have to pass the TreeView around.

Leave a Comment