【问题标题】:Missing library for ContextMenuContextMenu 缺少库
【发布时间】:2015-08-21 21:19:36
【问题描述】:

我正在使用代码来获取触发 ContextMenu 的控件的名称,但编译器在此行返回此消息:ContextMenu menu = menuItem.GetContextMenu();

MenuItem 不包含 GetContextMenu 的定义,并且发现没有扩展方法“GetContextMenu”接受“MenuItem”类型的第一个参数。可能缺少 using 指令或程序集引用。

同样的错误:

Control sourceControl = menu.SourceControl;

这是我的方法:

private void ClearTable_Click(object sender, RoutedEventArgs e)
    {
        // Try to cast the sender to a MenuItem
        MenuItem menuItem = sender as MenuItem;
        if (menuItem != null)
        {
            // Retrieve the ContextMenu that contains this MenuItem
            ContextMenu menu = menuItem.GetContextMenu();

            // Get the control that is displaying this context menu
            Control sourceControl = menu.SourceControl;
        }
    }

我必须添加哪个库?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    .GetContextMenu()System.Windows.Forms 命名空间(在 System.Windows.Forms.dll 中)中的 Menu 类的方法。因此,它不是为 WPF 控件而设计的……尽管通过一些调整可能是可能的。

    如果您在 WPF 中执行此操作,则需要使用 System.Windows.Controls 命名空间中的 ContextMenu 类及其方法。

    【讨论】:

    • 我用过:ContextMenu menuItem = sender as ContextMenu;但同样的错误返回..
    • ContextMenu 作为一个类存在于我在错误中列出的两个命名空间中,因此 ContextMenu menuItem = sender as ContextMenu; 可以工作。问题是,您的代码现在在 System.Windows.Controls 命名空间中使用 ContextMenu - 它没有 .GetContextMenu() 方法。
    • 好的,但是 GetContextMenu(); 有另一种方法?
    • 我只想获取通过 ContextMenu 触发事件的控件的名称,如下所示:stackoverflow.com/questions/4886327/…
    • 是的,所以这绝对超出了这个问题的范围,但我突然想到使用类似于 sender 参数的Parent 属性的东西。
    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2011-04-22
    • 2017-04-20
    • 2013-02-07
    相关资源
    最近更新 更多