Setting a WPF ContextMenu's PlacementTarget property in XAML?

我们两清 提交于 2019-11-27 01:51:19

问题


<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


回答1:


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>



回答2:


Have you tried this:

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

This will make the ContextMenu open where you right clicked your mouse (on the button). Which I think might be your desired location right?

--- EDIT --- In that case use this:

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

And in code behind:

private void ContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    // Get the button and check for nulls
    Button button = sender as Button;
    if (button == null || button.ContextMenu == null)
        return;
    // Set the placement target of the ContextMenu to the button
    button.ContextMenu.PlacementTarget = button;
    // Open the ContextMenu
    button.ContextMenu.IsOpen = true;
    e.Handled = true;
}

You can reuse the method for multiple buttons and ContextMenu's..




回答3:


You could use a <Menu />, styled as a Button and avoid the hassle with the ContextMenuService.



来源:https://stackoverflow.com/questions/1272251/setting-a-wpf-contextmenus-placementtarget-property-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!