簡體   English   中英

如何在 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..
}

或者有沒有更好的方法來做到這一點? 喜歡動態添加事件處理程序本身?

提前致謝。

ContextMenu 有一個名為SourceControl的屬性,MSDN 說它

獲取顯示快捷菜單的控件。

因此,您的事件處理程序可以從以這種方式作為發送方參數傳遞的 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)
        {
            ....
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM