如何在 C# 中创建用于编辑动态标签的事件处理程序?
How to create the event handler for editing dynamic labels in C#?
我在 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..
}
或者有更好的方法吗?喜欢动态添加事件处理程序本身?
提前致谢。
上下文菜单有一个名为 SourceControl
的 属性 并且 MSDN 说它
Gets the control that is displaying the shortcut menu.
因此您的事件处理程序可以通过这种方式从作为 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)
{
....
}
}
}
我在 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..
}
或者有更好的方法吗?喜欢动态添加事件处理程序本身?
提前致谢。
上下文菜单有一个名为 SourceControl
的 属性 并且 MSDN 说它
Gets the control that is displaying the shortcut menu.
因此您的事件处理程序可以通过这种方式从作为 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)
{
....
}
}
}