在Silverlight做逐帧事件可以用DispatcherTimer计时器,或使用一个空的Storyboard,在每次Completed事件中写你的执行代码然后再启动Storyboard,但是哪一种更好呢?这里有一个解释来自Adam Kinney:
The DispatcherTimer is a lower resolution timer than the timer behind the Storyboard class, which causes loss in fidelity. Additionally, the Storyboard execution is more stable across the different supported OSs and Browsers. I ll put together a sample to show the comparision.
不管怎样使用空的Storyboard来做逐帧是一个很好的解决方案,为此我设计了一个用于替代DispatcherTimer的StoryboardTimer类,可以在程序中和使用DispatcherTimer一样使用:
public class StoryboardTimer
{
private TimeSpan interval;
public TimeSpan Interval {
get { return interval; }
set {
interval = value;
sbTimer.Duration = new Duration(interval);
}
}
public event RoutedEventHandler Tick;
private void RaiseTick()
{
if (Tick != null)
{
Tick(this, new RoutedEventArgs());
}
}
Storyboard sbTimer;
private bool startFlag;
public static int StoryboardTimerCount = 0;
public StoryboardTimer()
{
sbTimer = new Storyboard();
startFlag = false;
sbTimer.Completed += new EventHandler(sbTimer_Completed);
(Application.Current).Resources.Add("sbTimer"+StoryboardTimer.StoryboardTimerCount, sbTimer);
StoryboardTimer.StoryboardTimerCount++;
}
void sbTimer_Completed(object sender, EventArgs e)
{
RaiseTick();
if (startFlag)
{
sbTimer.Begin();
}
}
public void Start()
{
startFlag = true;
sbTimer.Begin();
}
public void Stop()
{
startFlag = false;
}
}
使用方法
StoryboardTimer timer= new StoryboardTimer();
timer.Interval = TimeSpan.FromSeconds(frameRate);
timer.Tick += new RoutedEventHandler(timer_Tick);
void timer_Tick(object sender, RoutedEventArgs e)
{
//dosomething
}
This entry was written by , posted on June 27, 2008 at 8:02 am, filed under Silverlight. Bookmark the permalink. Follow any comments here with the RSS feed for this post.