在 XAML 中设置 WPF ContextMenu 的 PlacementTarget 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1272251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting a WPF ContextMenu's PlacementTarget property in XAML?
提问by kenwarner
<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
给我一个运行时错误“UIElement”类型没有公共 TypeConverter 类
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
并将 ContextMenu 放在屏幕的左上角,而不是按钮
回答by Tarsier
You should be setting the ContextMenuService.Placement attached property on the button, as stated in the remarks in the documentation for ContextMenu.Placement.
您应该在按钮上设置 ContextMenuService.Placement 附加属性,如ContextMenu.Placement文档中的备注所述。
<Button Name="btnFoo" Content="Foo" ContextMenuService.Placement="Bottom">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Bar" />
</ContextMenu>
</Button.ContextMenu>
</Button>
回答by Zenuka
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?
这将使 ContextMenu 在您右键单击鼠标(按钮上)的地方打开。我认为这可能是您想要的位置,对吗?
--- 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..
您可以对多个按钮和 ContextMenu 的..
回答by Lyra
You could use a <Menu />
, styled as a Button
and avoid the hassle with the ContextMenuService
.
您可以使用 a <Menu />
, 样式为 aButton
并避免使用ContextMenuService
.