【问题标题】:Open contextmenu on left mouse click wpf c#在鼠标左键单击 wpf c# 上打开上下文菜单
【发布时间】:2018-02-27 00:21:21
【问题描述】:

我有一个矩形。rectangle 有一个自定义的contextmenu(只是在<ContextMenu.Template>ControlTemplae 中进行了一些简单的更改)。我想要的是,单击鼠标左键,contextmenu 将弹出窗口。

我尝试在矩形的MouseDown 事件中添加rectangle1.contextmenu.isopen=true。是的,它会打开contextmenu。但是,contextmenu 设置为在矩形的上方(顶部)打开/弹出,我做到了只需将ContextMenuService.Placement="top" 添加到矩形的XAML。但是如果我在矩形的MouseDown 事件中使用rectangle1.contextmenu.isopen=true,那么contextmenu 会弹出但在错误的位置,它不再停留在顶部,而是跟随鼠标。例如如果我单击矩形的右上角,contextmenu 在右侧打开/弹出。这种行为很奇怪,我不知道为什么会这样。

无论如何,如何在鼠标左键单击矩形顶部打开contextmenu

更新

奇怪的是,无论我在mouseevents 中添加什么代码,上下文菜单都会丢失它的位置!例如,如果我什至在 mouseDown 事件上添加MsgBox("abc"),然后右键单击矩形,上下文菜单不在顶部!!

【问题讨论】:

  • 我已经通过那个 SO 帖子,但没有运气,我的是一个 rect,请阅读我的问题(contextmenu 不保持位置)

标签: c# wpf contextmenu


【解决方案1】:

正如我从 MSDN 参考资料中看到的那样 ContextMenu.Placement

当 ContextMenu 被分配给 FrameworkElement.ContextMenu 或 FrameworkContentElement.ContextMenu 属性, ContextMenuService 在 ContextMenu 打开。如果用户使用 鼠标,Placement 设置为 MousePoint。如果用户打开 通过使用键盘的 ContextMenu,将 Placement 设置为 Center。如果你 想要改变 ContextMenu 的位置,设置 FrameworkElement 上的 ContextMenuService.Placement 属性或 框架内容元素。

因此,由于您不是通过 ContextMenuService 执行此操作,因此您应该自己更改 Placement 和 PlacementTarget。

private void Mouse_Down(object sender, MouseButtonEventArgs e)
{
    var cm = ContextMenuService.GetContextMenu(sender as DependencyObject);
    if (cm==null)
    {
        return;
    }
    cm.Placement = PlacementMode.Top;
    cm.PlacementTarget = sender as UIElement;
    cm.IsOpen = true;
}

【讨论】:

    【解决方案2】:

    我想这就是你想要的?

    rect.ContextMenu.PlacementTarget = rect;
    
    rect.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
    rect.ContextMenu.IsOpen = true;
    
    // if you want it to be at the top and come down over the rectangle
    rect.ContextMenu.VerticalOffset = rect.ContextMenu.ActualHeight;
    

    【讨论】:

    • 我将代码添加到MouseDown 事件中,结果更奇怪......现在它在矩形上弹出
    猜你喜欢
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多