Alterning default Menu(Item) mouse reactions
I am making a customized menu, with customized menu Items. Changing control templates and styles have been oke, but now I would like to change the way mouse events effect the menuItems visibility.
By default, when you click a MenuItem within the pop up of a parent menu item, the pop up will collapse. When the mouse leaves the pop up stays open. I would like to reverse this, so that the pop up would only collapse when the mouse leaves, and that a sub menu Item can be clicked multiple times sequentially.
Is this possible ? and ifso how could I be able to do this ?
Any information providing 开发者_运维问答me with more insight, or leading to a solution is welcome!
Thanks
Use StaysOpenOnClick property on menuitems to keep the menu open on click.
A menu will close when it looses focus which is fine for me. If you want to automatically close the menu when the mouse is no longer on it you need to do this in code behind. Below code does this for the main menu by checking when the mouse is outside the area of the context menu. It only works for a menu with no submenu. If you want to use submenus you need to figure out when the mouse is over a sub menu and when not.
<Window x:Class="MenuTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid Background="Red">
<Grid.ContextMenu>
<ContextMenu MouseMove="ContextMenu_MouseMove">
<MenuItem Header="Menu Item" StaysOpenOnClick="True" />
<MenuItem Header="Menu Item" StaysOpenOnClick="True" />
<MenuItem Header="SubMenu">
<MenuItem Header="Menu Item" StaysOpenOnClick="True" />
</MenuItem>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</Window>
Event handler:
private void ContextMenu_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
ContextMenu contextMenu = sender as ContextMenu;
Point p = e.GetPosition(contextMenu);
contextMenu.IsOpen = p.X >= 0 && p.X <= contextMenu.ActualWidth && p.Y >= 0 && p.Y <= contextMenu.ActualHeight;
}
精彩评论