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

问题描述 投票:0回答:2

我有一个在表单1上运行的计时器,带有一个名为“timenumber”的标签显示时间,我还有一个带有标签“timer”的第二个表单。我如何以这两种方式同时链接这些值。表单1用作控制器,表单2是在另一个监视器中显示的表单。

c# winforms timer label
2个回答
1
投票

选项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相同的东西。


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();
}

在这里,_form2Form2展示的form1对象的参考。

你可以让Form2的房产是intdouble而不是string;您选择的可能取决于您是否对Form2中的值执行了其他操作。

© www.soinside.com 2019 - 2024. All rights reserved.