【问题标题】:How do I find the ContextMenuStrip that a ToolStripMenuItem belongs to?如何找到 ToolStripMenuItem 所属的 ContextMenuStrip?
【发布时间】:2012-10-01 09:14:44
【问题描述】:

我有一个ContextMenuStrip,其中一项具有DropDownItems 属性,它是动态添加的ToolStripMenuItem 对象的集合。当我处理子项Click 事件时,发送者的类型是ToolStripMenuItem,但它的OwnerToolStripDropDownMenu。我找不到如何从中确定“主机”ContextMenuStrip。它没有自己的Owner 属性,Parent 返回 null。

当我使用下面@Steve 发布的代码改编时:

Dim dropDownItem = DirectCast(sender, ToolStripDropDownItem)
Dim menu As ContextMenuStrip = DirectCast((((dropDownItem.DropDown).OwnerItem).OwnerItem).Owner, ContextMenuStrip)
Dim grid = menu.SourceControl

然后menu.SourceControlNothing,但是当我处理顶级时,即非下拉菜单项的点击是这样的

Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
Dim strip As ContextMenuStrip = DirectCast(item.Owner, ContextMenuStrip)
Dim grid As DataGridView = DirectCast(strip.SourceControl, DataGridView)

然后我得到了我正在寻找的网格。

【问题讨论】:

    标签: winforms contextmenu


    【解决方案1】:

    如果我理解正确,您希望从属于 ToolStripDropDownMenu 的 ToolStripMenuItem 的 Click 事件中访问 ContextMenuStrip 对象。

    如果是这样的话

       private void TestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem x = sender as ToolStripDropDownItem;
            if (x != null)
            {
                ContextMenuStrip k = (((x.DropDown).OwnerItem).OwnerItem).Owner as ContextMenuStrip;
                k.ForeColor = Color.Red; // as an example.
            }
        }
    

    【讨论】:

    • 这工作 98%,但由于某种原因,kSourceControl 属性为空,当我处理非下拉上下文菜单项的单击事件时它不为空,即顶级项目。
    猜你喜欢
    • 2013-11-28
    • 2014-03-22
    • 2011-09-13
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多