0

我真的是 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
    }

}

4

1 回答 1

0

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

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

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

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

这意味着“每当 thisLabel发生Text变化时,调用名为lblEnemyInfo_TextChanged”的函数。

此链接中有关于事件处理的良好文档(MSDN 文档)。

于 2016-08-21T05:22:13.463 回答