我如何检查i项是否已经存在于ToolStripMenuItem.DropDownItems

本文关键字:是否 存在 DropDownItems ToolStripMenuItem 何检查 检查 | 更新日期: 2023-09-27 17:51:18

我有一个ToolStripMenuItem MouseEnter事件:

private void recentFilesToolStripMenuItem_MouseEnter(object sender, EventArgs e)
{
    for (int i = 0; i < lines.Length; i++)
    {
        ToolStripMenuItem s = new ToolStripMenuItem(lines[i]);
            if (!recentFilesToolStripMenuItem.DropDownItems.ContainsKey(lines[i]))
            recentFilesToolStripMenuItem.DropDownItems.Add(s);
    }            
}

现在我使用ContainsKey,但之前我只尝试包含(s)在这两种情况下,它都会不断地向DropDownItems添加项目。每次我移动鼠标和输入,我看到项目再次添加。在这种情况下,lines是包含路径和文本文件名称的字符串数组。

例如在索引为0的行中,我看到:d:'mytext.txt

问题是当我用鼠标输入时,它会再次添加它们,而我希望它们只添加一次。

第一次看到用鼠标输入时:

d:'mytext.txt
e:'test.txt
c:'hello'hellowowrld.txt

下一次当我用鼠标输入时,我看到它两次:

d:'mytext.txt
e:'test.txt
c:'hello'hellowowrld.txt
d:'mytext.txt
e:'test.txt
c:'hello'hellowowrld.txt

然后下次我看到相同的项目9次,以此类推。

我如何检查i项是否已经存在于ToolStripMenuItem.DropDownItems

有两种方法。

第一,你创建你的ToolStripMenuItem像这样:

new ToolStripMenuItem(lines[i], (Image)null, (EventHandler)null, lines[i]);

第四个参数是.ContainsKey(...)的"关键",而不是第一个参数。

第二,你可以这样做:

if (!recentFilesToolStripMenuItem.DropDownItems
        .Cast<ToolStripMenuItem>()
        .Any(x => x.Text == lines[i]))
{
    recentFilesToolStripMenuItem.DropDownItems.Add(s);
}

第二种方法搜索实际文本。