Saturday, February 16, 2013

Timer in Silverlight

 

Have you seen timers in windows form? Pretty cool they were huh!! In silverlight we can also use timer which is pretty simple. But the question is why do we need Timers anyway? In case we want a particular set of code block to be executed at a regular specified interval of time, we use timers. So how to do that? Well let’s see.

I have created a silverlight project, and in the XAML of main page I have taken a text block. Here’s my MainPage’s xaml.

   1: <UserControl x:Class="Timers.MainPage"
   2:     xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:     mc:Ignorable="d"
   7:     d:DesignHeight="300" d:DesignWidth="400">
   8:  
   9:     <Grid x:Name="LayoutRoot" Background="Black">
  10:         <TextBlock x:Name="TxtCounter" Foreground="White" 
  11:                    VerticalAlignment="Center"
  12:                    HorizontalAlignment="Center"/>
  13:     </Grid>
  14: </UserControl>


Now in the code behind, we need to initialize timer. We are using Dispatcher Timer to fulfill our need for timer. Well, using Dispatcher timer is very simple. In the code behind of MainPage.xaml, in MainPage.cs, write the code below:


   1: readonly System.Windows.Threading.DispatcherTimer _mTimer = 
   2:             new System.Windows.Threading.DispatcherTimer();
   3: private int i = 0;
   4: public MainPage()
   5: {
   6:    InitializeComponent();
   7:    _mTimer.Interval= new TimeSpan(0, 0, 0, 0, 1000);
   8:    _mTimer.Tick += (sender, e) =>
   9:    {
  10:        TxtCounter.Text = i++.ToString(CultureInfo.InvariantCulture);
  11:    };
  12:    _mTimer.Start();
  13: }

Rest of the lines seems pretty simple and self explanatory, let’s talk about defining intervals for the timer.
The property Interval of DispatcherTimer is of type TimeSpan and take arguments as Timespan(days,hours,minutes,seconds,milliseconds). Isn’t that cool? You can even set the Timer’s tick interval to next century, so it will notify you when the century changes.
The tick event will occur every time for the interval of one second, and each time it occur, it will increment the value of “i” by 1 and display it in the TextBlock.
Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top