本篇介绍Silverlight 2.0的定时器。
很多时候,需要定时器来实现一些功能,定期或以某一个时间间隔定期触发事件,并可以控制定时器的时间间隔、开始和结束。Silverlight 2.0中,定时器有两种实习方法。StoryBoard和DispatcherTimer。
StoryBoard
StoryBoard唯一的事件是Completed,可用此事件触发计时动作;StoryBoard有Stop()、Pause()、Resume()、Begin()等方法可以控制计时动作;StoryBoard的Duration属性可以设置触发事件的时间间隔。但每一次事件完成,都要调用依此Begin()方法来开始下一次计时动作。
示例:
XAML:
<Grid x:Name="LayoutRoot" Background="DarkGreen">
<TextBlock x:Name="txtNow" Foreground="Yellow"></TextBlock>
<TextBlock x:Name="txtCount" Width="100" Height="60"
FontSize="50" Foreground="Yellow" Text="0" Loaded="txtCount_Loaded">
</TextBlock>
</Grid>
C#:
Storyboard s = null;
public Page()
{
InitializeComponent();
s = new Storyboard();
s.Duration = new Duration(TimeSpan.FromSeconds(1));
s.Completed += new EventHandler(s_Completed);
LayoutRoot.Resources.Add(s);
}
void s_Completed(object sender, EventArgs e)
{
txtCount.Text = (Convert.ToInt32(txtCount.Text) + 1).ToString();
txtNow.Text = DateTime.Now.ToString();
s.Begin();
}
private void txtCount_Loaded(object sender, RoutedEventArgs e)
{
s.Begin();
}
运行效果:
DispatcherTimer
DispatcherTimer所属的命名空间为:System.Windows.Threading,使用时需引入该命名空间。DispatcherTimer跟winform中的Timer类使用方法基本一致。唯一的事件Tick用来触发计时动作;Interval属性设置触发事件的时间间隔;Start()和Stop()方法控制计时动作;IsEnabled属性设置是否启用计时器。
示例:
XAML:
<Grid x:Name="LayoutRoot" Background="DarkGreen">
<TextBlock x:Name="txtNow" Foreground="Yellow"></TextBlock>
<TextBlock x:Name="txtCount" Width="100" Height="60"
FontSize="50" Foreground="Yellow" Text="0" Loaded="txtCount_Loaded">
</TextBlock>
</Grid>
C#:
DispatcherTimer timer = null;
public Page()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
}
void timer_Tick(object sender, EventArgs e)
{
txtCount.Text = (Convert.ToInt32(txtCount.Text) + 1).ToString();
txtNow.Text = DateTime.Now.ToString();
}
private void txtCount_Loaded(object sender, RoutedEventArgs e)
{
timer.Start();
}
运行效果:
结束语
Silverlight 2.0 的定时器在动画、特效处理等有很重要的作用。