在 FlowLayoutPanel 中只放置一个控件
Dispose only one control in FlowLayoutPanel
我正在编写通过按钮添加到 FlowLayoutPanel 的拖放标签的程序。一切正常,但我添加了 ContextMenu,其中只有一项用于删除 selected 标签。当右键单击标签和 select "delete" 我想处理这个特定的标签。之前可以用,现在不行了。
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();
}
感谢您的帮助。
你当然处理了错误的对象。它需要是 l
,无法获取它,因为您将其设为局部变量。最优雅的方法是用 lambda 表达式或匿名方法捕获它。请注意,错误的名称选择也会给您带来麻烦,您订阅了错误的 Click 事件。修复:
ContextMenuStrip cms = new ContextMenuStrip();
var deleting = cms.Items.Add("Delete");
deleting.Click += delegate { l.Dispose(); };
l.ContextMenuStrip = cms;
我正在编写通过按钮添加到 FlowLayoutPanel 的拖放标签的程序。一切正常,但我添加了 ContextMenu,其中只有一项用于删除 selected 标签。当右键单击标签和 select "delete" 我想处理这个特定的标签。之前可以用,现在不行了。
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();
}
感谢您的帮助。
你当然处理了错误的对象。它需要是 l
,无法获取它,因为您将其设为局部变量。最优雅的方法是用 lambda 表达式或匿名方法捕获它。请注意,错误的名称选择也会给您带来麻烦,您订阅了错误的 Click 事件。修复:
ContextMenuStrip cms = new ContextMenuStrip();
var deleting = cms.Items.Add("Delete");
deleting.Click += delegate { l.Dispose(); };
l.ContextMenuStrip = cms;