上的菜单项,以保持在菜单上单击打开使用StaysOpenOnClick财产。
当它失去焦点时,菜单将关闭,这对我来说很好。如果您想在鼠标不再位于其上时自动关闭菜单,则需要在代码后面执行此操作。下面的代码通过检查鼠标位于上下文菜单的区域之外来为主菜单执行此操作。它只适用于没有子菜单的菜单。如果你想使用子菜单,你需要弄清楚鼠标何时位于子菜单上,何时不是。
<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>
事件处理程序:
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;
}
谢谢!我无法相信我在msdn读过那个属性,你的信息完全是我想要的,非常感谢。 – 2010-05-28 10:12:50