The correct way to get the owner toolstrip of a toolstrip item in .net, winforms

泪湿孤枕 提交于 2019-12-08 03:30:59

问题


I found that while trying to find the owning toolstrip of an item, it wasn't a easy as just looking at the owner of the item. Below is some pseudo code that I think should work. Can anyone see any problems with this or should it work in all cases?

(1) Is type of Item.Owner a ToolStrip?

(2) Yes, Return Item.Owner

(3) No, Item = Item.OwnerItem. Go to (1).

ETA:

I'd like to make the test a general test. So instead of testing for ToolStrip, I should be testing for ToolStrip, MenuStrip, StatusStrip or ContextMenuStrip.

What makes the 4 mentioned above different to other ToolStrip derived controls such as ToolStripDropDown, ToolStripDropDownMenu and ToolStripOverflow?

ETA2: Ignore, absolute carp!

As far a I can tell, it's something to do with Control.TopLevelControl. The 3 controls above that can't be added to a form return a TopLevelControl of themselves. The 4 valid controls return nothing for TopLevelControl, before being added to a form, and then the form itself, after being added.


回答1:


This worked:

        ToolStrip owner = testToolStripMenuItem.Owner;
        while (owner is ToolStripDropDownMenu)
            owner = (owner as ToolStripDropDownMenu).OwnerItem.Owner;



回答2:


If you are handling a click event for a drop down menu item as follows:

 private void testItemToolStripMenuItem_Click(object sender, EventArgs e)
 {
    ToolStripDropDownItem item = sender as ToolStripDropDownItem;
    ToolStripDropDown menu = item.DropDown;
    ToolStripItem ownerItem = item.OwnerItem;
    ToolStrip toolStrip = item.Owner;
 }



回答3:


Try item.Parent instead of item.Owner.



来源:https://stackoverflow.com/questions/2255351/the-correct-way-to-get-the-owner-toolstrip-of-a-toolstrip-item-in-net-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!