根据标题文本访问 MenuItemCollection
我正在使用 ContextMenu
< /a> 并添加了一些菜单
到菜单项
< a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.menu.menuitemcollection.aspx" rel="nofollow">MenuItemCollection
通过执行以下操作:
private const string ADD_MENU_ITEM = "Add";
private const string REMOVE_MENU_ITEM = "Remove";
...
mContextMenu.MenuItems.Add(ADD_MENU_ITEM, new EventHandler(...));
mContextMenu.MenuItems.Add(REMOVE_MENU_ITEM, new EventHandler(...));
...
现在稍后,我想从 MenuItemCollection
访问 Menu
基于标题文本。像这样的事情:
Menu m = mContextMenu.MenuItems[ADD_MENU_ITEM]; // This doesnt work
我知道我可以使用索引,但我觉得应该有一种方法可以根据标题名称获取 Menu
,因为这就是它的添加方式。
我该怎么做?
I am using a ContextMenu
and have added some Menu
's to the MenuItems
MenuItemCollection
by doing the following:
private const string ADD_MENU_ITEM = "Add";
private const string REMOVE_MENU_ITEM = "Remove";
...
mContextMenu.MenuItems.Add(ADD_MENU_ITEM, new EventHandler(...));
mContextMenu.MenuItems.Add(REMOVE_MENU_ITEM, new EventHandler(...));
...
Now later, I would like to access the Menu
from the MenuItemCollection
based on the caption text. So something like this:
Menu m = mContextMenu.MenuItems[ADD_MENU_ITEM]; // This doesnt work
I know that I could use the index, but I feel like there should be a way to get the Menu
based on the caption name, since that is how its added.
How might I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我有类似的问题。
我们不能通过标题,我们必须枚举项目并比较文本。
I had a similar problem.
We can't go by caption, we have to enumerate through items and compare the text.
您无法使用现有的 API 来做到这一点 - 您必须发挥创意。我知道这是有道理的,因为这就是您调用构造函数的方式,但这只是他们在创建新菜单项时节省时间的方式,而不是内部组织方式。
我可能会维护一个 System.Collections.Generic.Dictionary,其键是标题字符串,值是对 MenuItem 对象的引用,然后创建一个包装函数,将菜单项添加到菜单和字典中。当菜单项更改时删除这些词典条目是不同的练习。
You can't do that using the existing API - you have to get creative. I know it makes sense because that's how you call the constructor, but that's just their way of saving you time when making new MenuItems, not how it's organized internally.
I might maintain a System.Collections.Generic.Dictionary whose keys are the caption strings, and values are references to the MenuItem objects, then create a wrapper function that adds the menu item to the menu and the Dictionary. Removing those Dictionary entries when the menu items change is a different exercise.
您可以尝试(我假设 C#3 或更高版本)
在相关说明中,我不知道您的意图是什么,但您可能想看看
Tag
属性>菜单项。它是专门为存储私人数据而设计的,这样您就不必依赖标题或词典来存储信息。You can try (I'm assuming C#3 or higher)
On a related note, I don't know what your intentions are but you might want to take a look at the
Tag
property inMenuItem
. Is is specifically made to store private data so that you don't have to rely on the caption or dictionaries to store information.