Timer
andTimer_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);
}
}
}
}
上面极其简化的示例展示了如何在对象事件触发时使用 adelegate
和event
topublish
通知。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