[英]Context menu items and subitems
I have a ContextMenuStrip inside a form. 我在表单内有一个ContextMenuStrip。
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. PS:我无法添加图片,因为我是这个论坛的新手,请明白我的意思,希望您能明白。
Thanks! 谢谢!
You need to cast to ToolStripDropDownItem
and check the DropDownItems
property. 您需要转换为
ToolStripDropDownItem
并检查DropDownItems
属性。 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. 由于按照MSDN,ToolStripButton,ToolStripLabel,ToolStripSeparator,ToolStripControlHost,ToolStripDropDownItem,ToolStripStatusLabel确实继承自ToolStripItem,因此您可以尝试使用as运算符进行强制转换,然后再设置其text属性。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.