C# - 获取ToolStripMenuItem的父级

时间:2010-12-31 23:45:49

标签: c# winforms

如何确定ToolStripMenuItem的父级?使用普通的MenuStrip,您只需使用Parent属性,但ToolStripMenuItem似乎没有该属性。我有一个ToolStripDropDownButton,它有几个ToolStripMenuItems,我希望能够以编程方式精确定位那些父类。

5 个答案:

答案 0 :(得分:19)

尝试OwnerItem属性。

答案 1 :(得分:5)

这对我有用:

ToolStripMenuItem menuItem = sender as ToolStripMenuItem;

ToolStrip toolStrip = menuItem.GetCurrentParent();

...从这里开始,您可以设计一种方法,将您从随机ToolStripMenuItem带到最高级别:

public static class ToolStripItemExtension
{
    public static ContextMenuStrip GetContextMenuStrip(this ToolStripItem item)
    {
        ToolStripItem itemCheck = item;            

        while (!(itemCheck.GetCurrentParent() is ContextMenuStrip) && itemCheck.GetCurrentParent() is ToolStripDropDown)
        {
            itemCheck = (itemCheck.GetCurrentParent() as ToolStripDropDown).OwnerItem;
        }

        return itemCheck.GetCurrentParent() as ContextMenuStrip;
    }
}

答案 2 :(得分:3)

试试这个......

ToolStripMenuItem t = (ToolStripMenuItem)sender;
ContextMenuStrip s = (ContextMenuStrip)t.Owner;
MessageBox.Show(s.SourceControl.Name);

答案 3 :(得分:0)

这就是你要找的东西

private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
    contextMenuStrip1.Tag = ((ContextMenuStrip)sender).OwnerItem;
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
    ToolStripMenuItem senderItem = (ToolStripMenuItem)sender;
    var ownerItem = (ToolStripMenuItem)((ContextMenuStrip)senderItem.Owner).Tag;
}

答案 4 :(得分:0)

在搜索了许多关于该问题的帖子后,我发现这对我有用:

ToolStripMenuItem mi = (ToolStripMenuItem)sender;
ToolStripMenuItem miOwnerItem = (ToolStripMenuItem)(mi.GetCurrentParent() as ToolStripDropDown).OwnerItem;