鼠标离开时关闭上下文菜单

时间:2017-06-01 15:44:00

标签: wpf contextmenu

简单的问题 - 当鼠标光标离开ContextMenu时,不会调用MouseLeave事件,为什么会这样? 我想在鼠标光标离开时关闭ContextMenu。 这是一个小样本:

app.modules.ts

1 个答案:

答案 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;
}