2016-11-14 59 views
-1

訪問對象的Click事件中,我做了一個類標籤類標籤如何通過代碼

class label 
{ 
    public Label l; 
    public Label acess() 
    { 
     l = new Label(); 
     l.Text = "asdad"; 
     l.Left=100; 
     l.Top =100; 
     return l; 
    } 
    public Label lab 
    { 
     get 
     { 
      return l; 
     } 
     set 
     { 
      l = value; 
     } 
    } 

} 

,並調用此方法並初始化它在窗體上現在

Label l; 
    label cls; 
    public MainForm() 
    { 

     InitializeComponent(); 




     cls = new label(); 
     l = new Label(); 
     l =cls.acess(); 
     this.Controls.Add(l); 

    } 

我可以訪問我的標籤( 「L」)像

cls.lab.Click = //anything 

,但我不知道如何使用這個說法,我只知道如何使用點擊e到‘實驗室’「點擊」選項通過標籤事件通風口,但我不知道如何使用這個(通過代碼)。 我該如何使用它,如果我要檢查標籤的文本,像

cls.lab.Click = { 

if(lab.text=="i am the old label") 
{ 
    lab.text = "i am the new label"; 
} 
    } 

請給我解釋一下,給個詳細的解答。

+0

你使用什麼框架,WPF,winforms?你最需要繼承一些控制,比如'UserControl'來獲取事件 – thumbmunkeys

+0

你是否在問[事件處理程序](http://stackoverflow.com/q/803242/1997232)? – Sinatr

+0

@thumbmunkeys我想使用Winforms – ShoaibSivany

回答

1

您添加一個事件監聽器這樣的標籤:

public MainForm() 
{ 
    InitializeComponent(); 

    cls = new label(); 
    l =cls.acess(); 
    l.Click += cls_Clicked; 
    this.Controls.Add(l); 
} 

private void cls_Click(object sender, EventArgs e) 
{ 
    Label clickedLabel = sender as Label; 
    if(clickedLabel == null) return; 

    if(clickedLabel.Text=="i am the old label") 
    { 
     clickedLabel.Text = "i am the new label"; 
    } 
} 

我不能現在就測試它,但它應該工作,假設你使用的WinForms。

+0

一個小錯誤,請檢查編輯後的版本。 – ChronosMOT

+0

有沒有任何選項可以查看編輯過的版本,還是應該簡單地刷新我的頁面? – ShoaibSivany

+0

我不確定,刷新應該工作。該更改在MainForm構造函數中。我錯過了cls.access()返回了一個Label。所以l.lab.Click失敗。仍然未經測試,但 – ChronosMOT