这是最简单的实现定时器的方式。你可以在你的程序中直接使用HtmlTimer类,它位于System.Windows.Browser命名空间下,使用之前你需要在工程中先加入对System.Silverlight.dll的引用。它的使用方法很简单:
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>
<Storyboard x: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>
<EventTrigger RoutedEvent="Canvas.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard x: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的信息,还可以参考下文: