【问题标题】:How to create the event handler for editing dynamic labels in C#?如何在 C# 中创建用于编辑动态标签的事件处理程序?
【发布时间】:2016-04-23 18:21:25
【问题描述】:

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

或者有更好的方法吗?喜欢动态添加事件处理程序本身?

提前致谢。

【问题讨论】:

  • 这个事件与什么相关联?它似乎是按钮上的一个事件,但您想要访问与该按钮关联的标签。您可以通过其实例访问标签,或者如果您需要它更加动态,则需要将标签与按钮相关联。这可以通过多种方式完成。最好的方法完全取决于您的应用程序是如何设计的以及您有什么要求。
  • 您可以通过object sender检索它。看看this extensive answer,它描述得很好。
  • @khlr 不可能。事件处理程序附加到 ContextMenu,发送者是 ContextMenu。

标签: c# winforms label contextmenu


【解决方案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)
        {
            ....
        }
    }
}

【讨论】:

  • 你能解释一下 if 语句实际检查的是什么吗?我只需要编辑标签。编辑用户右键单击的标签。基本上改变那个特定标签的属性。
  • 防止NullReferenceExceptions
  • 这是一种习惯。在这种情况下,可能存在的每个对象引用都不会为空,但添加一个简单的空值检查是一个救命稻草,当您与愤怒的客户打错电话时,您可以学会使用它
猜你喜欢
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
相关资源
最近更新 更多