2014-01-28 35 views
0

請您幫助我,我如何更改不同類中的標籤文本?如何更改不同類中的標籤文本(C#)

基本WinForm的腳本:

public partial class buildEditor : Form 
{ 
    public buildEditor() 
    { 
     InitializeComponent(); 
     Label maxSkillPoint = new Label(); 
     maxSkillPoint.AutoSize = true; 
     maxSkillPoint.BackColor = System.Drawing.Color.Transparent; 
     maxSkillPoint.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); 
     maxSkillPoint.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(193)))), ((int)(((byte)(196)))), ((int)(((byte)(181))))); 
     maxSkillPoint.Location = new System.Drawing.Point(528, 687); 
     maxSkillPoint.Name = "maxSkillPoint"; 
     maxSkillPoint.Text = UniqueValue.spentSkillPoints.ToString(); 
     maxSkillPoint.Size = new System.Drawing.Size(0, 20); 
     this.Controls.Add(maxSkillPoint); 
    } 

    public void maxSkillPoint_TextChanged(Form formInstance, string labelName) 
    { 
     // Get reference to the label 
     var label = formInstance.Controls.Find(labelName, true).FirstOrDefault(); 
     if (null != label && label is Label) 
     { 
      (label as Label).Text = "test"; 
     } 
    } 
} 

我創建了隔壁班的,這將是對maxSkill文本更改文本。

public class ChangeTextForMaxSkill() 
{ 
    Button button = new Button(); 

    public ChangeTextForMaxSkill() 
    { 
     button.Click += new EventHandler(changeText); 
    } 

    private void changeText(object sender, EventArgs e) 
    { 
     // Get reference to the label 
     var buildEditor = new buildEditor(); 
     buildEditor.maxSkillPoint_TextChanged(buildEditor, "maxSkillPoint"); 
    } 
} 

我真的thx所有的答案。

+0

你從哪裏調用'changeText()'? –

+0

我編輯了我的第一篇文章,以調用changeText(); –

+0

您的按鈕及其單擊事件應位於Form(BuildEditor)上,而不在ChangeTextForMaxSkill()類上。此按鈕僅用於測試,將其添加到視覺設計器中。我不知道你的項目的其餘部分,但檢查我的更新的整個代碼的答案。 –

回答

1

首先,您的命名約定不符合標準慣例。類和方法名都應該使用大寫的第一個字母,而不是像你所做的那樣。我在我的答案中使用了適當的命名約定。

您必須將BuildEditor *表單的instance傳遞給您的ChangeTextForMaxSkill.ChangeText()函數。

接下來,標籤對象maxSkill不是您的BuildEditor類的屬性。因此,您需要在表單中實際找到對該控件的引用,因爲您正在動態添加它。

​​

如果你想測試它,只需添加您的窗體上的一個按鈕,並在按鈕單擊處理測試:

private void button1_Click(object sender, EventArgs e) 
{ 
    var changeTextForMaxSkill = new ChangeTextForMaxSkill(); 
    changeTextForMaxSkill.ChangeText(this, "MaxSkil"); 
} 

我測試過這一點也適用:)

+0

我現在嘗試它,請等待:) –

+0

它不爲我工作,我編輯我的第一篇文章,你能檢查我做得不好嗎? –

+0

對於命名約定的解釋並不完全正確,因爲外殼是可見的不是對象類型,公共項目通常是大寫字母,受保護的是小寫字母和小寫字母,也可以是小寫字母或小寫字母,前綴爲_,這樣可以一目瞭然你可以看到你的編輯對象是本地的還是全局的 – MikeT

3

我得到了它很簡單: 交出你的外部類的構造函數的Label控件:

using System.Windows.Forms; 

public class Yourclass{ 

    private Label UpdateLabel; 
    public Yourclass (Label yourLabel) 
    { 
     this.UpdateLabel = yourlabel; 
    } 

    private void action() 
    { 
     //here is your update of the label 
     UpdateLabel.Text = "Your text"; 
    } 

} 

在窗體類,打造 「yourclass」 和手的一個實例在標籤:

Yourclass cls = new Yourclass(Label1);