我有这个任务要完成:有一个上下文菜单,其中一个分支中有 3 个静态项目(通过设计器创建),之后会有动态创建的项目(链接到硬盘驱动器上一个文件夹的子文件夹)。这是我用来创建项目的代码的一部分:
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && listBox1.SelectedIndex != -1)
{
string pathDatosString = Path.Combine(PMVars.MainPath + clientsbox2.SelectedItem.ToString() + @"\" + listBox1.SelectedItem.ToString() + @"\01-Datos");
int count = ((contextMenuStrip1.Items[2] as ToolStripMenuItem).DropDownItems[2] as ToolStripMenuItem).DropDownItems.Count;
//MessageBox.Show(count.ToString());
if (count > 3)
{
for (int i = 3;i < count;i++)
{
((contextMenuStrip1.Items[2] as ToolStripMenuItem).DropDownItems[2] as ToolStripMenuItem).DropDownItems.RemoveAt(i);
}
}
if (Directory.Exists(pathDatosString))
{
// This path is a directory
foreach (string diritem in Directory.GetDirectories(pathDatosString))
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Click += new EventHandler(OpenDir);
string dirCutted = diritem.Split('\\').Last();
((contextMenuStrip1.Items[2] as ToolStripMenuItem).DropDownItems[2] as ToolStripMenuItem).DropDownItems.Add(dirCutted, null, OpenDir) ;
}
}
contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
}
}
所以我遇到的问题是每次启动listbox1_mouseclick - 项目被一次又一次地创建(克隆)所以我尝试检查是否已经存在带有文本的项目,但弹出错误说集合已更改. 我认为这是因为我正在收集动态创建的项目?此代码适用于删除,但也许有更优雅的解决方案?