Implementing Threading in Silverlight Applications
<UserControl x:Class='SilverlightApplication3.MainPage' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:d='http://schemas.microsoft.com/expression/blend/2008' xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' mc:Ignorable='d' d:DesignWidth='640' d:DesignHeight='480'> <Grid x:Name="LayoutRoot" Background="Black"> <TextBlock x:Name="myText"/> <Button x:Name="myButton" Content="Start Clock" VerticalAlignment="Bottom"/> </Grid> </UserControl> //File: Page.xaml.cs using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; namespace SilverlightApplication3 { public partial class MainPage : UserControl { DispatcherTimer timer; bool isTicking; public MainPage() { InitializeComponent(); isTicking = false; timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 0, 1, 0); // 1 Second timer.Tick += new EventHandler(UpdateClock); myButton.Click += new RoutedEventHandler(StartClock); } public void StartClock(object o, RoutedEventArgs sender) { if (isTicking) { myButton.Content = "Start Clock"; timer.Stop(); isTicking = false; } else { myButton.Content = "Stop Clock"; timer.Start(); isTicking = true; } } public void UpdateClock(object o, EventArgs sender) { this.myText.Text = String.Format("{0:T}", DateTime.Now); } } }