如何找到ToolStripMenuItem所属的ContextMenuStrip?

时间:2012-10-01 09:14:45

标签: winforms contextmenu

我有一个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)
然后我得到了我正在寻找的网格。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望从属于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.
        }
    }