c# - 更改时自动从全局变量更新标签

标签 c# winforms events label auto-update

这是我的程序。

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        static int count = 0;

        public Form1(){InitializeComponent();}

        private void button1_Click(object sender, EventArgs e)
        {
            count += 1;
            label1.Text = Convert.ToString(count);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            count -= 1;
            label1.Text = Convert.ToString(count);
        }
    }
}

现在...我有一个程序,每当我们按下两个按钮之一并将值保存到全局变量 count 中,然后将其显示在 label1 中时,该程序将数字加 1 或减 1。

假设我想更改另一个标签 (label2) 的值,其中我还想在每次 label1 更改时显示计数变量值的内容。

所以有一种方法,使用按钮中的事件,可以这样完成:

private void button1_Click(object sender, EventArgs e)
{
    count += 1;
    label1.Text = Convert.ToString(count);
    label2.Text = Convert.ToString(count);
}

private void button2_Click(object sender, EventArgs e)
{
    count -= 1;
    label1.Text = Convert.ToString(count);
    label2.Text = Convert.ToString(count);
}

问题来了...

但是假设我想更新 label2 的值,而不是从按钮事件中更新,而是以某种方式更新它,以便它会在 count 变量发生变化时自动更新值。

请帮忙。

最佳答案

在这种情况下使用属性

private int count
private int Count
{
    get { return count; }
    set 
    { 
       count = value;
       RefreshLabels();
    }
}

private void RefreshLabels()
{
    label1.Text = Convert.ToString(count);
    label2.Text = Convert.ToString(count);
}

当你想改变计数时,只需使用属性即可

Count += 1;
Count -= 1;

关于c# - 更改时自动从全局变量更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5754003/

相关文章:

c# - 可以给 Html.DropDownListFor() 选项标签一个值吗?

c# - 如何访问面板中的控件在 C# 中

c# - 以编程方式从 wpf 应用程序打开 winform

json - 在 Elm 中,如何检测一组元素是否会失去焦点?

angularjs - 如何在 Angular 指令中对按键事件进行单元测试

javascript - document.removeEventListener javascript

c# - RestBody,在C#中创建Json Payload导致冲突,因为Key是c#关键字

c# - 在 RowUpdating (ASP.NET GridView) C# 期间获取 GridView 内标签的旧值

c# - Process.Start() 从命令提示符窗口获取错误

c# - httpClient 告诉我错误 c# winform