繁体   English   中英

如何检查ToolStripMenuItem.DropDownItems中是否已经存在我?

[英]How do i check if i tem already exist in ToolStripMenuItem.DropDownItems?

我有一个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但是在我只尝试使用Contains(s)之前,在这两种情况下,它都会不断地将这些项一次又一次地添加到DropDownItems中。 每次我移动鼠标并按Enter时,我都会看到再次添加的项目。 在这种情况下,行是包含文本文件的路径和名称的字符串数组。

例如d:\\mytext.txt索引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次,依此类推。

有两种方法可以做到这一点。

一种是您像这样创建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);
}

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

暂无
暂无

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

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