Silverlight 1.1/2.0 Alpha Timer |
In silverlight 1.1/2.0 alpha there are a lot of things that just do not work as us spoiled developers would expect.
One of these things is the fact that a normal Timer event cannot access the UI Thread. Meaning you cannot change any visual things with a normal timer.
There are some fixes around, I added some of them together in a simple class u can use as seen in the following example:
public partial class Page : Canvas { UITimer _Timer; public void Page_Loaded(object o, EventArgs e) { // Create a new UITimer _Timer = new UITimer(this); // With a 10 seconds interval _Timer.Duration = new TimeSpan(0, 0, 10); // And call this delegate every 10 seconds _Timer.TimerEvent += new EventHandler(_Timer_TimerEvent); } void _Timer_TimerEvent(object sender, EventArgs e) { // Do something in the UI // Fore example: Set the opacity of the page Opacity = 0.5; } }
The class itself looks like this:
using System.Windows; using System; using System.Windows.Media.Animation; public class UITimer { static int TimerCount = 0; private bool _Active = false; public bool Active { get { return _Active; } set { if (_Active != value) { _Active = value; if (_Active) { timer.Duration = _Duration; timer.Begin(); } else timer.Stop(); } } } private Duration _Duration; public Duration Duration { get { return _Duration; } set { _Duration = value; timer.Duration = _Duration; } } public event EventHandler TimerEvent; Storyboard timer; public UITimer(FrameworkElement rootElement) { timer = (Storyboard)XamlReader.Load(String.Format(“<Storyboard xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” x:Name=”UITimer_{0}” Duration=”00:00:00″ />”,UITimer.TimerCount)); timer.Completed += new EventHandler(timer_Completed); rootElement.Resources.Add(timer); UITimer.TimerCount++; } void timer_Completed(object sender, EventArgs e) { if (TimerEvent != null) TimerEvent(this, EventArgs.Empty); } }
Source Code : UITimer.zip
Light it up!
Robertjan Tuit














RSS English
RSS Nederlands





