Setting a WPF ContextMenu's PlacementTarget property in XAML?

kenwarner picture kenwarner · Aug 13, 2009 · Viewed 22.6k times · Source
<Button Name="btnFoo" Content="Foo" >
    <Button.ContextMenu Placement="Bottom" PlacementTarget="btnFoo">
        <MenuItem Header="Bar" />
    </Button.ContextMenu>
</Button>

gives me a runtime error 'UIElement' type does not have a public TypeConverter class

I also tried

<Button Name="btnFoo" Content="Foo" >
    <Button.ContextMenu Placement="Bottom" PlacementTarget="{Binding ElementName=btnFoo}">
        <MenuItem Header="Bar" />
    </Button.ContextMenu>
</Button>

and that put the ContextMenu in the top left corner of my screen, rather than at the Button

Answer

Tarsier picture Tarsier · Jun 18, 2010

You should be setting the ContextMenuService.Placement attached property on the button, as stated in the remarks in the documentation for ContextMenu.Placement.

<Button Name="btnFoo" Content="Foo" ContextMenuService.Placement="Bottom">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Bar" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>