WPF中鼠标左键单击Button弹出ContextMenu,让其右键ContextMenu失效
文章分类:.net编程在目前的WPF版本中,很多的控件都有一个ContextMenu的属性,可以设置组件的右键菜单,这点确实是很方便,但是有些时候我们可能会需要当单击鼠标左键才弹出这个ContextMenu,而不是单击鼠标右键(即:当单击鼠标右键的时候不弹出该ContextMenu),这样我们就能很方便的实现类似Flex中设置弹出式菜单的效果...
这是默认的右键菜单:
首先:
然后,设置一下:
Xaml代码- <ButtonName="btnMenu"Width="50"Height="25"Content="菜单"Initialized="btnMenu_Initialized">
- <Button.ContextMenu>
- <ContextMenuName="contextMenu">
- <MenuItemHeader="复制"/>
- <MenuItemHeader="粘贴"/>
- <MenuItemHeader="剪切"/>
- <MenuItemHeader="删除"/>
- </ContextMenu>
- </Button.ContextMenu>
- </Button>
<Button Name="btnMenu" Width="50" Height="25" Content="菜单" Initialized="btnMenu_Initialized"><Button.ContextMenu><ContextMenu Name="contextMenu"><MenuItem Header="复制"/><MenuItem Header="粘贴"/><MenuItem Header="剪切"/><MenuIt em Header="删除"/></ContextMenu></Button.ContextMenu></Button>
看Initialized="btnMenu_Initialized"的实现:
C#代码- privatevoidbtnMenu_Initialized(objectsender,EventArgse)
- {
- //设置右键菜单为null
- this.btnMenu.ContextMenu=null;
- }
private void btnMenu_Initialized(object sender, EventArgs e){ //设置右键菜单为null this.btnMenu.ContextMenu = null; }
接着,设置单击鼠标左键弹出菜单:
C#代码- privatevoidbtnMenu_Click(objectsender,RoutedEventArgse)
- {
- //目标
- this.contextMenu.PlacementTarget=this.btnMenu;
- //位置
- this.contextMenu.Placement=PlacementMode.Top;
- //显示菜单
- this.contextMenu.IsOpen=true;
- }
private void btnMenu_Click(object sender, RoutedEventArgs e){ //目标 this.contextMenu.PlacementTarget = this.btnMenu; //位置 this.contextMenu.Placement = PlacementMode.Top; //显示菜单 this.contextMenu.IsOpen = true; }
好了,运行,单击按钮,效果: