C# – 获取ToolStripMenuItem的父级

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

尝试OwnerItem属性。

这对我有用:

 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; } } 

试试这个…..

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

这就是你要找的东西

 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; }