Loop through subitems in menustrip
質問
Well i've tried this:
private IEnumerable<ToolStripMenuItem> GetItems(ToolStripMenuItem item)
{
foreach (ToolStripMenuItem dropDownItem in item.DropDownItems)
{
if (dropDownItem.HasDropDownItems)
{
foreach (ToolStripMenuItem subItem in GetItems(dropDownItem))
yield return subItem;
}
yield return dropDownItem;
}
}
private void button2_Click_1(object sender, EventArgs e)
{
List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem toolItem in menuStrip1.Items)
{
allItems.Add(toolItem);
MessageBox.Show(toolItem.Text);
allItems.AddRange(GetItems(toolItem));
}
}
but i only get File
, Edit
, View
i need to reach Export
(see the figure) and its subitem
, and maybe change the visibility of Word
for example.
NOTE: the form
changes the menustrip
item dynamically thats why i need to loop through them.
解決
based on the details you provided you can use linq as
var exportMenu=allItems.FirstOrDefault(t=>t.Text=="Export");
if(exportMenu!=null)
{
foreach(ToolStripItem item in exportMenu.DropDownItems) // here i changed the var item to ToolStripItem
{
if(item.Text=="Word") // as you mentioned in the requirements
item.Visible=false; // or any variable that will set the visibility of the item
}
}
hope that this will help you
regards
他のヒント
In order to get all the menu items (ToolStripMenuItem instances) in your MenuStrip use the following code (I assume the MenuStrip name is menuStrip1)
// Get all the top menu items, e.g. File , Edit and View
List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
// For each of the top menu items, get all sub items recursively
allItems.AddRange(GetItems(item));
}
所属していません StackOverflow