Implementing Threading in Silverlight Applications : Thread « Data « Silverlight






Implementing Threading in Silverlight Applications

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);
         }
    }
}

   
    
    
  








Related examples in the same category

1.Updating the UI from a Background ThreadUpdating the UI from a Background Thread
2.Implementing the DoWork eventImplementing the DoWork event
3.Reporting progress changes from the BackgroundWorkerReporting progress changes from the BackgroundWorker
4.Handling the completion of the background taskHandling the completion of the background task
5.Event Dispatcher TimerEvent Dispatcher Timer
6.No Background WorkerNo Background Worker
7.Canceling a BackgroundWorker when a user selects the Escape keyCanceling a BackgroundWorker when a user selects the Escape key
8.Event Dispatcher with ThreadEvent Dispatcher with Thread