在Silverlight 2以前的版本里中有很多不同的方法来模拟Timer.其中最流行的方法就是用StoryBoard来完成.在结束时不停的调用自己.
例如:
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();
}
}
{
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();
}
}
客户端这样调用:
Timer t
=
new
Timer();
Container.Children.Add(t);
t.TimerFired += new Timer.TimerFiredHandler(t_TimerFired);
t.StartTimer();
void t_TimerFired()
{
// Do Stuff here.
}
Container.Children.Add(t);
t.TimerFired += new Timer.TimerFiredHandler(t_TimerFired);
t.StartTimer();
void t_TimerFired()
{
// Do Stuff here.
}
现在可以使用DispatcherTimer:
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.
}
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.
}
原文:http://pagebrooks.com/archive/2008/03/07/silverlight-2-has-a-timer-dispatchertimer.aspx