在Silverlight 2以前的版本里中有很多不同的方法来模拟Timer.其中最流行的方法就是用StoryBoard来完成.在结束时不停的调用自己.
例如:
代码语言:js复制public partial class Timer : UserControl
{
public delegate void TimerFiredHandler();
public event TimerFiredHandler TimerFired;
public Timer()
{
InitializeComponent();
TimeUnit.Completed = new EventHandler(TimeUnit_Completed);
}
void TimeUnit_Completed(object sender, EventArgs e)
{
TimeUnit.Begin();
if (TimerFired != null)
TimerFired();
}
public void StartTimer()
{
TimeUnit.Begin();
}
}
客户端这样调用:
代码语言:js复制Timer t = new Timer();
Container.Children.Add(t);
t.TimerFired = new Timer.TimerFiredHandler(t_TimerFired);
t.StartTimer();
void t_TimerFired()
{
// Do Stuff here.
}
现在可以使用DispatcherTimer:
代码语言:js复制System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = new TimeSpan(0, 0, 0, 0, 500); // 500 Milliseconds
dt.Tick = new EventHandler(dt_Tick);
dt.Start();
void dt_Tick(object sender, EventArgs e)
{
// Do Stuff here.
}