如何以2种不同形式链接2个标签

时间:2019-02-18 14:01:39

标签: c# winforms timer label

我有一个在表单1上运行的计时器,其中有一个名为“ timenumber”的标签显示了时间,我还有一个具有标签“ timer”的第二种表单。如何将它们链接在一起,使它们在同一时间具有相同的值。窗体1用作控制器,窗体2是在另一台监视器中显示的窗体。

2 个答案:

答案 0 :(得分:1)

选项1
使用其构造函数将对Form1中的倒数标签的引用传递给Form2,然后使用此引用来订阅标签的TextChanged事件:

Form1 中:

private int CountDown = 100;

private void button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2(this.[The Counter Label]);
    form2.Show();
    this.timer1.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.[The Counter Label].Text = CountDown.ToString();
    if (CountDown == 0)
        this.timer1.Enabled = false;
    CountDown -= 1;
}

Form2 中:

public form2() : this(null) { }

public form2(Control timerCtl)
{
    InitializeComponent();
    if (timerCtl != null) {
        timerCtl.TextChanged += (s, evt) => { this.[Some Label].Text = timerCtl.Text; };
    }
}

选项2
使用可以设置为控件引用的Form2公共属性。在创建Form1的新实例之后,立即在Form2中设置此属性。
但是,这意味着Form1需要了解 Form2中的此属性:

Form1 中:

private int CountDown = 100;

private void button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.Show();
    form2.CountDownControl = this.[The Counter Label];
    this.timer1.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.[The Counter Label].Text = CountDown.ToString();
    if (CountDown == 0)
        this.timer1.Enabled = false;
    CountDown -= 1;
}

Form2 中:

private Control timerCtl = null;

public Control CountDownControl {
    set { this.timerCtl = value;
        if (value != null) {
            this.timerCtl.TextChanged += (s, evt) => { this.[Some Label].Text = timerCtl.Text; };
        }
    }
}

还有许多其他选项。

您还可以在Form2中使用公共属性,并直接在Timer.Tick事件中设置此属性。如第二个示例所示,公共属性可以将其控件之一的Text属性设置为该属性的值。
我不太喜欢这个选项,尽管它可用。

Form1 中:

private int CountDown = 100;

private void button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.Show();
    this.timer1.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.[The Counter Label].Text = CountDown.ToString();
    form2?.CountDownValue = CountDown;
    if (CountDown == 0)
        this.timer1.Enabled = false;
    CountDown -= 1;
}

Form2 中:

public int CountDownValue {
    set { this.[Some Label].Text = value.ToString(); }
    }
}

您还可以在Form1中创建一个自定义事件,Form2可以订阅或实现 INotifyPropertyChange 。但这是与Option1相同的东西。

答案 1 :(得分:0)

如果form1打开form2,这很容易。在Form2中,定义一个属性以设置标签上的文本:

public string TimerText 
{
  set => _timerLabel.Text = value;
}

您可能还需要调用_timerLabel.Invalidate();来强制刷新标签。

然后,当form1中的倒数计时器更新时,只需在form2中设置该属性:

private void Timer_Tick(object sender, EventArgs e)
{
  // calculate remaining time
  _form2.TimerText = remainingTime.ToString();
}

在这里,_form2是对Form2正在显示的form1对象的引用。

您可以将Form2中的属性设为intdouble而不是string;选择哪种选项取决于您是否对Form2中的值进行其他操作。