我在Windows窗体上单击按钮时创建了一个动态标签。然后右键单击标签。我正在显示上下文菜单“cm”。我显然想要为上下文菜单项添加功能。但我不明白的是如何在事件处理程序中引用“lbl”对象?如何在名为MarkedImportant和EditLabel的事件处理程序中编辑标签的属性?
public void btnMonSub_Click(object sender, EventArgs e)
{
string s = txtMonSub.Text;
Label lbl = new Label();
lbl.Text = s;
lbl.Location = new System.Drawing.Point(205 + (100 * CMonSub), 111);
CMonSub++;
lbl.Size = new System.Drawing.Size(100, 25);
lbl.BackColor = System.Drawing.Color.AliceBlue;
this.Controls.Add(lbl);
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Mark Important", MarkImportant);
cm.MenuItems.Add("Edit", EditLabel );
lbl.ContextMenu = cm;
}
private void MarkImportant(object sender, EventArgs e)
{
// imp..
}
private void EditLabel(object sender, EventArgs e)
{
// edit..
}
或者有更好的方法吗?就像动态添加事件处理程序本身一样?
提前致谢。
答案 0 :(得分:1)
ContextMenu有一个名为SourceControl
的属性,MSDN说它
获取显示快捷菜单的控件。
因此,您的事件处理程序可以通过这种方式从作为 sender 参数传递的MenuItem到达ContextMenu
private void MarkImportant(object sender, EventArgs e)
{
// Convert the sender object to a MenuItem
MenuItem mi = sender as MenuItem;
if(mi != null)
{
// Get the parent of the MenuItem (the ContextMenu)
// and read the SourceControl as a label
Label lbl = (mi.Parent as ContextMenu).SourceControl as Label;
if(lbl != null)
{
....
}
}
}