简单的问题 - 当鼠标光标离开ContextMenu时,不会调用MouseLeave事件,为什么会这样? 我想在鼠标光标离开时关闭ContextMenu。 这是一个小样本:
app.modules.ts
答案 0 :(得分:2)
您可以处理MouseLeave
的内部Border
元素的ContextMenu
事件。
处理Loaded
本身的ContextMenu
事件,在可视化树中找到Border
元素,并将事件处理程序连接到其MouseLeave
事件:
<Button Content="Right-click me!" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button.ContextMenu>
<ContextMenu Loaded="ContextMenu_Loaded">
<MenuItem Header="Menu item 1" />
<MenuItem Header="Menu item 2" />
<Separator />
<MenuItem Header="Menu item 3" />
</ContextMenu>
</Button.ContextMenu>
</Button>
private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
{
ContextMenu cm = sender as ContextMenu;
Border border = GetChildOfType<Border>(cm);
border.MouseLeave += Border_MouseLeave;
}
private void Border_MouseLeave(object sender, MouseEventArgs e)
{
//do something here...
}
private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null)
return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null)
return result;
}
return null;
}