简体   繁体   English

动态添加上下文菜单项

[英]Dynamically adding Context Menu items

For some reason, regardless of how many times the toolstripmenuitem is added to the context menu, it always says the context menu does not contain the item. 出于某种原因,无论tooltripmenuitem添加到上下文菜单的次数多少,它总是说上下文菜单不包含该项。

ToolStripMenuItem Colour = new ToolStripMenuItem("Colour");

ctmFile.Show(Cursor.Position);
Selecteditem = lvFiles.FocusedItem.Text.ToString();
if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder")
{

    if (ctmFile.Items.Contains(Colour) == false)
    {
        ctmFile.Items.Add(Colour);
    }

}
else
{
    if(ctmFile.Items.Contains(Colour))
    {
        ctmFile.Items.Remove(Colour);
    }
}

You are creating a new menu item and searching for that. 您正在创建一个新菜单项并搜索它。 But since it was just created, it obviously can't already be in the menu. 但由于它刚刚创建,它显然不能在菜单中。 That's why you never find it there. 这就是为什么你永远不会在那里找到它。 A different menu item with that text may have been added before, but your code is not looking for that one. 之前可能已添加了具有该文本的不同菜单项,但您的代码并未查找该代码。

You need to search the menu items for an item that has that text. 您需要在菜单项中搜索包含该文本的项目。 The code can be simplified a bit in other ways: 代码可以通过其他方式简化:

var colorItemText = "Colour";
var colorMenuItem = ctmFile.Items.Cast<ToolStripMenuItem>()
                      .FirstOrDefault(mi => mi.Text == colorItemText);

if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder")
{
    //  Create and add if not already present
    if (colorMenuItem == null)
    {
        colorMenuItem = new ToolStripMenuItem(colorItemText);
        ctmFile.Items.Add(colorMenuItem);
    }
}
else if (colorMenuItem != null)
{
    //  Remove if already present. 
    ctmFile.Items.Remove(colorMenuItem);
}

Just to add on top of Ed's answer, I would recommend using keys instead: 只是为了补充Ed的答案,我建议使用键代替:

ctmFile.Show(Cursor.Position);
Selecteditem = lvFiles.FocusedItem.Text.ToString();
if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder")
{

    if (!ctmFile.Items.ContainsKey("Colour")) 
    {
        ToolStripMenuItem Colour = new ToolStripMenuItem("Colour");
        Colour.Name= "Colour"; //Add a name (key) to your menu.
        ctmFile.Items.Add(Colour);
    }

}
else
{
    if (ctmFile.Items.ContainsKey("Colour")) 
    {
        ctmFile.Items.RemoveByKey("Colour");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM