如何在C#中创建用于编辑动态标签的事件处理程序?

时间:2016-04-23 18:21:26

标签: c# winforms label contextmenu

我在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..
}

或者有更好的方法吗?就像动态添加事件处理程序本身一样?

提前致谢。

1 个答案:

答案 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)
        {
            ....
        }
    }
}