public partial class TestWindow : Window { public TestWindow() { InitializeComponent(); eventInit(menu1.Items); } public void eventInit(ItemCollection items) { foreach (var item in items) { MenuItem menuItem = item as MenuItem; //给每个菜单项添加鼠标事件,鼠标移入就打开菜单 menuItem.MouseEnter += (sendr, e) => { menuItem.IsSubmenuOpen = true;//不加这句就不会有问题,但是不加就达不到要的效果 }; //有子项就递归 if (menuItem.HasItems) { eventInit(menuItem.Items); } } } }
<Window x:Class="Card.TestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="TestWindow" Height="853" Width="407" > <Grid> <Menu Height="87" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top" Width="200" Background="Transparent"> <Menu.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Vertical"></StackPanel> </ItemsPanelTemplate> </Menu.ItemsPanel> <MenuItem Header="1" Background="Transparent" > <MenuItem Header="1-1" Background="Transparent"> <MenuItem Header="1-1-1" Background="Transparent" /> <MenuItem Header="1-1-2" Background="Transparent" /> <MenuItem Header="1-1-3" Background="Transparent" /> <MenuItem Header="1-1-4" Background="Transparent" /> </MenuItem> <MenuItem Header="1-2" Background="Transparent"> <MenuItem Header="1-2-1" Background="Transparent" /> <MenuItem Header="1-2-2" Background="Transparent" /> <MenuItem Header="1-2-3" Background="Transparent" /> <MenuItem Header="1-2-4" Background="Transparent" /> </MenuItem> </MenuItem> </Menu> </Grid> </Window>
MouseEventHandler mouseEventHandler = (sendr, e) => { menuItem.IsSubmenuOpen = true; }; menuItem.MouseEnter += mouseEventHandler; menuItem.MouseLeave += mouseEventHandler;
算是折中的解决办法吧,打开再关闭,中间还是会闪一下
不知大侠能解释一下为何会引发Menu的关闭事件吗?
@灰机_不会飞: 我也解析不了,象这样发生关闭的,我移了十几二十下才发生一下,所以只能折中让它移开时,不触发关闭
@Yu: 这么说具体是跟机器有关咯?在我这里是百分百会出现的,不过这种延迟还算可以忍受,先把这问题留着吧,谢谢你了。