Label的文本在没有textchanged事件处理程序的情况下更改了吗?为什么?

时间:2016-08-21 02:17:13

标签: c# winforms label hardcoded

我是C#的新手,在没有事件处理程序的帮助下,当我将其设置为不同的值时,我一直在想为什么标签文本会改变?

这是我的代码:

class Main_Program : Form
{
    Button btnAttack = new Button();
    Label[] lblEnemyInfo = new Label[4];
    public Main_Program()
    {
        btnAttack.Text = "ATTACK";
        btnAttack.Location = new Point(350, 450);
        btnAttack.Width = 150;
        btnAttack.Height = 50;
        btnAttack.FlatStyle = FlatStyle.Popup;
        btnAttack.MouseClick += new MouseEventHandler(btnAttack_MouseClick);

        for (short i = 0; i < 4; i++)
            lblEnemyInfo[i] = new Label();

        string enemyHealth = "Health : " + enemy.Health; //I'm going set the values on label 2
        lblEnemyInfo[1].Text = enemyHealth;
        lblEnemyInfo[1].Font = new Font("Segoi UI", 12, FontStyle.Italic);
        lblEnemyInfo[1].Location = new Point(500, 50);

        for (short i = 0; i < 4; i++)
            Controls.Add(lblEnemyInfo[i]);
    }
    private void btnAttack_MouseClick(Object sender, EventArgs e)
    {
        short totalDamage = totalDamageDeal(enemy.Armor, player.Attack);
        string log = "You Attack the enemy, you deal " + totalDamage + " damage";
        enemy.Health -= totalDamage;
        string result = "Health : " + enemy.Health;
        lblEnemyInfo[1].Text = result;
        lblEnemyInfo[1].TextChanged += new EventHandler(lblEnemyInfo_TextChanged); //The label's text changed even without the eventhandler
    }
    private void lblEnemyInfo_TextChanged (object sender, EventArgs e)
    {
         //i don't know what statements to put here
    }

}

1 个答案:

答案 0 :(得分:0)

EventHandler用于在事件发生时执行代码。如果您不希望发生任何事情,请不要使用事件处理程序。

在您的情况下,lblEnemyInfoLabel。它有一个名为Label.Text的属性(字符串类型)。您可以更改此值以更新Label显示的字符串。使用lblEnemyInfo[1].Text = "Health Down";将使相应的Label显示值“Health Down”,无论事件处理程序是否与之关联。

您正在使用以下代码为Label设置事件处理程序:

lblEnemyInfo[1].TextChanged += new EventHandler(lblEnemyInfo_TextChanged);

这意味着“每当此Label Text发生更改时,请调用名为lblEnemyInfo_TextChanged的函数”。

有关于事件处理的良好文档in this link(MSDN文档)。