我有一个ContextMenu
我Button
想在一个MouseEnter
事件上打开的,而不是在默认的右键单击事件上。这是我的 XAML:
<Button Content="Button" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave">
<Button.ContextMenu>
<ContextMenu>
.... context menu items ....
</ContextMenu>
</Button.ContextMenu>
</Button>
以及相关的事件处理程序:
private void Button_MouseEnter(object sender, MouseEventArgs e)
{
backButtonContextMenu.Placement = PlacementMode.Bottom;
backButtonContextMenu.IsOpen = true;
Console.WriteLine("MouseEnter called");
}
private void Button_MouseLeave(object sender, MouseEventArgs e)
{
backButtonContextMenu.IsOpen = false;
Console.WriteLine("MouseLeave called");
}
很直接。不幸的是,当鼠标悬停在按钮上时,这两种方法被无限调用,来回交替。这是我的控制台中的输出示例:
MouseEnter called
MouseLeave called
MouseEnter called
MouseLeave called
MouseEnter called
MouseLeave called
MouseEnter called
MouseLeave called
... etc. ...
我假设这与 ContextMenu 在打开时窃取焦点有关,或者可能放置某种不可见的“帮助”背景以检测何时需要关闭。有没有人对这种行为有解释,有没有办法避免它?从 UI 的角度来看,这是一个非常简单的效果。