开发者

Context menu items and subitems

开发者 https://www.devze.com 2023-04-01 07:13 出处:网络
I have a ContextMenuStrip inside a form. For some reason, 开发者_运维知识库I want to change all items of the context menu simultaneously. So I wrote this peace of code:

I have a ContextMenuStrip inside a form.

For some reason, 开发者_运维知识库I want to change all items of the context menu simultaneously. So I wrote this peace of code:

int a = 0; 

foreach (ToolStripItem co in contextMenuStrip1.Items)  
{     
 co.Text = "Menu" + a.ToString();
  a++;
  }

But although the main items change succesfully, the subitems doesn't change So how can I have access to those subitems too?

PS: I cannot add an image because I am new to this forum to see what I mean, I hope you get the idea.

Thanks!


You need to cast to ToolStripDropDownItem and check the DropDownItems property. And, of cource, update it recursively.

here is the sample:

public void ChangeMenuItemsNames(ToolStripItemCollection collection)
    {
        foreach (ToolStripMenuItem item in collection)
        {
            item.Name = "New Name";

            if (item is ToolStripDropDownItem)
            {
                ToolStripDropDownItem dropDownItem = (ToolStripDropDownItem)item;

                if (dropDownItem.DropDownItems.Count > 0)
                {
                    this.ChangeMenuItemsNames(dropDownItem.DropDownItems);
                }
            }
        }
    }

How to use:

   this.ChangeMenuItemsNames(this.contextMenuStrip1.Items);


Since as per MSDN, ToolStripButton,ToolStripLabel,ToolStripSeparator,ToolStripControlHost,ToolStripDropDownItem,ToolStripStatusLabel do inherit from ToolStripItem, you can try casting with as operator and then setting its text property as well.

Hope this is what your asking for.


  void ChangeName(ToolStripItemCollection collection, ref int a)
    {
        foreach (ToolStripItem co in collection)
        {
            co.Text = "Menu" + a.ToString();
            a++;
            if (co is ToolStripDropDownItem)
            {
                ToolStripDropDownItem ts = co as ToolStripDropDownItem;
                if (ts.DropDownItems != null) ChangeName(ts.DropDownItems, ref a);
            }
        }
    }
0

精彩评论

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

关注公众号