[英]How do i check if i tem already exist in ToolStripMenuItem.DropDownItems?
I have a ToolStripMenuItem
MouseEnter
event: 我有一个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);
}
}
Now I am using ContainsKey
but before i tried only with Contains(s) In both cases it keep adding the items over and over again to the DropDownItems. 现在,我正在使用ContainsKey
但是在我只尝试使用Contains(s)之前,在这两种情况下,它都会不断地将这些项一次又一次地添加到DropDownItems中。 Each time i move the mouse and Enter i see the items added again. 每次我移动鼠标并按Enter时,我都会看到再次添加的项目。 In this case lines is array of string contain paths and names of text files. 在这种情况下,行是包含文本文件的路径和名称的字符串数组。
For example in lines index 0 i see: d:\\mytext.txt
例如d:\\mytext.txt
索引0中,我看到: d:\\mytext.txt
The problem is that it keep adding them over again when i enter with the mouse and i want them to be added only once. 问题是当我用鼠标进入并且我只希望将它们添加一次时,它会继续添加它们。
First time i see when entering with the mouse: 我第一次看到用鼠标进入时:
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
Next time when I enter with the mouse I see it twice: 下次当我用鼠标进入时,会看到两次:
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
Then next time i see the same items 9 times and so on. 然后下一次我看到相同的项目9次,依此类推。
There are two ways to do this. 有两种方法可以做到这一点。
One, is that you create your ToolStripMenuItem
like this: 一种是您像这样创建ToolStripMenuItem
:
new ToolStripMenuItem(lines[i], (Image)null, (EventHandler)null, lines[i]);
It's that fourth parameter that is the "key" for .ContainsKey(...)
, not the first parameter. 第四个参数是.ContainsKey(...)
的“键”,而不是第一个参数。
Two, you can do it this way: 二,您可以通过以下方式进行操作:
if (!recentFilesToolStripMenuItem.DropDownItems
.Cast<ToolStripMenuItem>()
.Any(x => x.Text == lines[i]))
{
recentFilesToolStripMenuItem.DropDownItems.Add(s);
}
This second way searches the actual text. 第二种方法搜索实际文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.