我有一个在表单1上运行的计时器,带有一个名为“timenumber”的标签显示时间,我还有一个带有标签“timer”的第二个表单。我如何以这两种方式同时链接这些值。表单1用作控制器,表单2是在另一个监视器中显示的表单。
选项1
使用其构造函数将对Form1
中的Count Down标签的引用传递给Form2
,然后使用此引用来订阅Label的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
使用可以设置为Control引用的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
事件设置此属性。与第二个示例一样,public属性可以将其中一个控件的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相同的东西。
如果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
的房产是int
或double
而不是string
;您选择的可能取决于您是否对Form2
中的值执行了其他操作。