我正在使用Drag& Drop标签添加按钮添加到FlowLayoutPanel。它工作得很好,但我添加了ContextMenu,只有一个项目用于删除所选标签。右键单击标签并选择"删除"我想处理这个特定的标签。它工作正常,但现在却没有。
void fillFLP(FlowLayoutPanel FLP)
{
Label l = new Label();
l.AutoSize = true;
l.Text = textBox.Text;
l.BackColor = Color.Red;
l.Width = 150;
l.AutoSize = true;
l.MaximumSize = new Size(150, 200);
l.MinimumSize = new Size(150, 25);
l.Padding = new Padding(5);
l.Margin = new Padding(25, 5, 25, 0);
ContextMenuStrip deleting= new ContextMenuStrip();
deleting.Items.Add("Delete");
deleting.Click += new System.EventHandler(this.delete);
l.ContextMenuStrip = deleting;
FLP.Controls.Add(l);
l.MouseDown += l_MouseDown;
l.MouseMove += l_MouseMove;
l.MouseUp += l_MouseUp;
}
private void delete(object sender, EventArgs e)
{
this.Dispose();
}
感谢您的帮助。
答案 0 :(得分:2)
你当然正在处理错误的对象。它必须是l
,无法访问它,因为它使它成为局部变量。最优雅的方法是使用lambda表达式或匿名方法捕获它。请注意,糟糕的名称选择也会让您遇到麻烦,您订阅了错误的Click事件。修正:
ContextMenuStrip cms = new ContextMenuStrip();
var deleting = cms.Items.Add("Delete");
deleting.Click += delegate { l.Dispose(); };
l.ContextMenuStrip = cms;