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
andevent
を使用する方法を示しています。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