定时器(Timer)是一个挺常见的功能。通过使用定时器, 可以每隔一段制定的时间后触发某一指定的事件,如刷新、定时提醒等等。那在Silverlight中怎么使用定时器呢?其实也很简单,且听我细细道来。:)
HtmlTimer类和Storyboard
HtmlTimer timer = new HtmlTimer();
timer.Interval = 200; //200毫秒
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
void timer_Tick(object sender, EventArgs e)
{
//在这里处理定时器事件
}
<Canvas.Resources>
<Storyboardx:Name="timer"Completed="timer_Tick" />
timer.Duration = new TimeSpan(0, 0, 0, 0, 200); //200毫秒
timer.Begin();
void timer_Tick(object sender, EventArgs e)
{
//在这里处理定时器事件
timer.Begin();
定时器控件
public class XamlControl : Control
{
private readonly FrameworkElement m_Container;
protected FrameworkElement Container
{
get { return m_Container; }
}
protected XamlControl(string xamlName)
{
Stream stream = GetType().Assembly.GetManifestResourceStream(xamlName);
if (stream == null)
{
throw new ArgumentException("Xaml resource " + xamlName + " not present", "xamlName");
}
using (StreamReader sr = new StreamReader(stream))
{
string xamlData = sr.ReadToEnd();
m_Container = base.InitializeFromXaml(xamlData);
}
}
<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Canvas.Triggers>
<EventTriggerRoutedEvent="Canvas.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboardx:Name='timer'>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Canvas.Triggers>
</Canvas>
public class Timer : XamlControl
{
private Storyboard m_Timer;
public Timer()
: base("SilverlightControl.Timer.xaml")
{
if (Container == null) return;
m_Timer = Container.FindName("timer") as Storyboard;
m_Timer.Completed += OnComplete;
}
public TimeSpan Interval
{
get
{
return m_Timer.Duration.TimeSpan;
}
set
{
m_Timer.Duration = new Duration(value);
}
}
public event EventHandler<EventArgs> Tick;
private void FireTick()
{
Tick(this, new EventArgs());
}
private void OnComplete(object sender, EventArgs e)
{
FireTick();
m_Timer.Begin();
}
Timer timer = new Timer();
timer.Interval = new TimeSpan(0, 0, 0, 0, 200);
timer.Tick += timer_tick;
关于Timer的信息,还可以参考下文:
原文链接: 在Silverlight中使用定时器(Timer)