我有一个表单,其中有一个名为 labelTime
的标签。
在另一个名为 TimeCalculate
的类中,我有一个带有 Timer_tick
事件处理程序的 Timer
。
在这个类中,我还有一个函数 GetTime()
,它以字符串格式返回时间。
我希望此字符串出现在每个 Timer_tick
的 labelTime
中。
有办法实现吗?
public void MyTimer(Label o_TimeLabel)
{
Timer Clock = new Timer();
Clock.Tag = o_TimeLabel.Text;
Clock.Interval = 1000; Clock.Start();
Clock.Tick += new EventHandler(Timer_Tick);
}
private void Timer_Tick(object sender, EventArgs eArgs)
{
if (sender == Clock)
{
//LabelTime.Text = GetTime(); <-- I want this to work!
}
}
最佳答案
Timer
和 Timer_Tick
事件不需要与您的 Label
属于同一类,您可以创建一个简单的自定义事件来发布/订阅您的 Timer_Tick
event
.
你的 TimeCalculate
类:
namespace StackOverflow.WinForms
{
using System;
using System.Windows.Forms;
public class TimeCalculate
{
private Timer timer;
private string theTime;
public string TheTime
{
get
{
return theTime;
}
set
{
theTime = value;
OnTheTimeChanged(this.theTime);
}
}
public TimeCalculate()
{
timer = new Timer();
timer.Tick += new EventHandler(Timer_Tick);
timer.Interval = 1000;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
TheTime = DateTime.UtcNow.ToString("dd/mm/yyyy HH:mm:ss");
}
public delegate void TimerTickHandler(string newTime);
public event TimerTickHandler TheTimeChanged;
protected void OnTheTimeChanged(string newTime)
{
if (TheTimeChanged != null)
{
TheTimeChanged(newTime);
}
}
}
}
上面极其简化的示例显示了如何使用 delegate
和 event
至 publish
Timer_Tick
时的通知Timer
对象事件触发。
在 Timer_Tick
时需要通知的任何对象事件触发(即您的时间已更新)只需要 subscribe
给您的自定义事件发布者:
namespace StackOverflow.WinForms
{
using System.Windows.Forms;
public partial class Form1 : Form
{
private TimeCalculate timeCalculate;
public Form1()
{
InitializeComponent();
this.timeCalculate = new TimeCalculate();
this.timeCalculate.TheTimeChanged += new TimeCalculate.TimerTickHandler(TimeHasChanged);
}
protected void TimeHasChanged(string newTime)
{
this.txtTheTime.Text = newTime;
}
}
}
我们创建了一个 TimeCalcualte
的实例在订阅 TimerTickHandler
之前上课指定处理通知的方法 ( TimeHasChanged
) 的事件。注意 txtTheTime
是我给的名字TextBox
在我的表格上。
关于c# - 如何从不同类中的计时器事件处理程序更新标签文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17746338/