このタスクを実行する必要があります: contextmenustrip があり、ブランチの 1 つに 3 つの静的アイテム (デザイナーを介して作成) があり、その後、動的に作成されたアイテム (ハード ドライブ上の 1 つのフォルダーのサブフォルダーへのリンク) があります。ここでは、アイテムを作成するために使用しているコードの一部です:
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 が開始されるたびに - アイテムが何度も作成されている (クローン) ということです。 . 私が収集している動的に作成されたアイテムが原因だと思いますか? このコードは削除に機能しますが、これにはもっと洗練された解決策があるのではないでしょうか?