C# - Get Parent of ToolStripMenuItem

前端 未结 5 1497
说谎
说谎 2020-12-16 14:33

How can I determine the parent of a ToolStripMenuItem? With a normal MenuStrip all you have to do is use the Parent property, but it doesn\'t seem that ToolStripMenuItem ha

相关标签:
5条回答
  • 2020-12-16 14:50

    Here is what you looking for

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 15:01

    This works for me:

    ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
    
    ToolStrip toolStrip = menuItem.GetCurrentParent();
    

    ...from this, you can devise a method to bring you from a random ToolStripMenuItem to the top-most level such:

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-16 15:02

    Try the OwnerItem property.

    0 讨论(0)
  • 2020-12-16 15:02

    Try this.....

    ToolStripMenuItem t = (ToolStripMenuItem)sender;
    ContextMenuStrip s = (ContextMenuStrip)t.Owner;
    MessageBox.Show(s.SourceControl.Name);
    
    0 讨论(0)
  • 2020-12-16 15:02

    After searching many post to this question, I found that this worked for me:

    ToolStripMenuItem mi = (ToolStripMenuItem)sender;
    ToolStripMenuItem miOwnerItem = (ToolStripMenuItem)(mi.GetCurrentParent() as ToolStripDropDown).OwnerItem;
    
    0 讨论(0)
提交回复
热议问题