开发者

C# - Get Parent of ToolStripMenuItem

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 has that property.开发者_JAVA技巧 I have a ToolStripDropDownButton that has a couple of ToolStripMenuItems and I'd like to be able to pinpoint the parent of those programatically.


Try the OwnerItem property.


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


Try this.....

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜