如何更改不同类别的标签文本(C#)

时间:2014-01-28 21:29:40

标签: c# winforms class button label

如何更改不同类别的标签文字?现在,我使用这个脚本,但标签没有改变。

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

调试查找控件:

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

1 个答案:

答案 0 :(得分: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");
    }
}