Silverlight 1.1/2.0 Alpha Timer |
In Silverlight 1.1/2.0 alpha gaan nog een heleboel dingen fout waarvan je, als verwende ontwikkelaar, verwacht dat ze gewoon werken.
Een van die issues is dat een normale Timer geen aanpassingen meer kan doen aan User Interface. Je krijgt dan de foutmelding dat de Thread niet bij de UI mag.
Er zijnj hiervoor meerdere oplossingen te vinden op internet, waarvan ik er een aantal heb samengevoegd in een simpele class, die je zo kan gebruiken :
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; } }
De UITimer class ziet er zo uit :
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





