飘遥的Blog

C/C++/.NET
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

乱弹琴 Silverlight 2.0 (19) 定时器

Posted on 2008-05-06 03:42  Zzx飘遥  阅读(1245)  评论(0编辑  收藏  举报
前言:Silverlight 2.0 Beta1 已经发布,加入了许多激动人心的新特性:WPF UI 框架、丰富的控件、丰富的网络支持、丰富的基础类库支持等。这是本人的学习笔记,写的比较乱,因此定名为乱弹琴Silverlight 2.0 系列文章。

本篇介绍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 的定时器在动画、特效处理等有很重要的作用。