簡體   English   中英

在沒有foreach循環的情況下獲取特定Tag的ToolStripMenuItem.DropDownItems的索引

[英]Get index of ToolStripMenuItem.DropDownItems for specific Tag without foreach loop

有沒有一種方法可以在不使用foreach循環的情況下獲取具有特定標簽的集合中某個項目的ToolStripMenuItem.DropDownItems索引?

我目前正在這樣做:

private void button1_Click(object sender, EventArgs e)
{
    Form2 myForm2 = new Form2();
    myForm2.OnTemplateUpdated += new Form2.TemplateUpdatedHandler(myForm2_OnTemplateUpdated);
    myForm2.Show();
}

void myForm2_OnTemplateUpdated(Form s, TemplateUpdatedEvent e)
{
    int index = 0;
    foreach (ToolStripMenuItem myMenuItem in templatesToolStripMenuItem.DropDownItems)
    {
        if ((string)myMenuItem.Tag == e.TemplateId)
        {
            templatesToolStripMenuItem.DropDownItems[index].Text = e.NewName;
            break;
        }
        index++;
    }
}

我知道templatesToolStripMenuItem.DropDownItems具有IndexOf()方法,但是我沒有運氣嘗試像這樣使用它:

int menuItemIndex = templatesToolStripMenuItem.DropDownItems
    .IndexOf(new ToolStripMenuItem() { Tag = e.TemplateId });

menuItemIndex始終為-1 ...也許我使用的方法不正確?

您可以為DropDownItems的項目分配名稱,該名稱與它們的Tag相對應。 例如:

templatesToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem("Item text") { Tag = 1, Name = "item1" });

因此,您可以按以下方式獲得所需的物品:

templatesToolStripMenuItem.DropDownItems["item" + e.TemplateId].Text = e.NewName;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM