2014-01-28 55 views
-1

如何更改不同類中的標籤文本?現在,我使用這個腳本,但標籤沒有改變。如何更改不同類中的標籤文本(C#)

Winform的腳本:

public partial class buildEditor : Form 
{ 
    ChangeTextForMaxSkill skill = new ChangeTextForMaxSkill(this); 

    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"; 
     } 
    } 
} 

我創建了隔壁班的,這將是對maxSkillPoint標籤改變文本,但它不工作。

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"); 
    } 
} 

調試find的控制:

buildEditor {test.buildEditor, Text: test} test.buildEditor 
this {test.ChangeTextForMaxSkill} test.ChangeTextForMaxSkill 
+0

什麼不行呢?它會拋出異常嗎?文字是不是變了? –

+0

是的,標籤上的文字未在「測試」中更改 –

+0

您是否嘗試過調試以查看'label'在調用Find後是否爲空? –

回答

1

你正在改變當地的按鈕實例的文本。你想要的是先獲得對原始按鈕的引用。 附加到該按鈕的事件,並在那裏改變字符串。

使用此:

public class ChangeTextForMaxSkill 
{ 
    buildEditor editor; 

    public ChangeTextForMaxSkill(buildEditor editor) // inject reference to form 
    { 
     this.editor = editor; 
     Button button = new Button(); 
     button.Click += new EventHandler(changeText); 
     form.Controls.Add(button); 
    } 

    private void changeText(object sender, EventArgs e) 
    { 
     // Get reference to the label 
     editor.maxSkillPoint_TextChanged(editor, "maxSkillPoint"); 
    } 
} 
+0

我編輯我的第一篇文章。你的腳本對我有錯誤。 因爲我在buildEditor中使用這個表格: ChangeTextForMaxSkill skill = new ChangeTextForMaxSkill(); (對於一些下一個函數) –

+0

然後,只需使用'new ChangeTextForMaxSkill(this);'代替。 – pid

+0

我再次編輯我的第一篇文章和錯誤是這樣的: 錯誤關鍵字'this'在當前上下文中不可用 –