×
Namespaces

Variants
Actions

Implement timers in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article explains how to implement a timer (DispatcherTimer) in Windows Phone.

SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Tested with
Devices(s): Windows Phone Emulator
Compatibility
Platform(s): Windows Phone 7.5, 8
Windows Phone 8
Windows Phone 7.5
Article
Keywords: dispatchertimer, windows phone
Created: girishpadia (13 Oct 2011)
Last edited: hamishwillee (16 Jul 2013)

Contents

Introduction

The code example shows how to use DispatcherTimer on Windows Phone. Timers are very useful for executing code at specified time intervals.

WindowsPhoneClock.jpg

Implementation

The code in this article is written using C#. A text box will be used to display a clock, which is refreshed every second. Follow the below steps to create the clock app:

  1. Create a new "Silverlight" project using C# language. Here we are naming the project as "Clock"
  2. Place a text box and a button.
  3. We are giving textbox name as "txtClock". We can also change the font and color of content in the text box.
  4. We will now add following code to the project.
using System; 
using Microsoft.Phone.Controls;
using System.Windows.Threading;
namespace Clock
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
void OnTimerTick(Object sender, EventArgs args)
{
// text box property is set to current system date.
// ToString() converts the datetime value into text
txtClock.Text = DateTime.Now.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
// creating timer instance
DispatcherTimer newTimer = new DispatcherTimer();
// timer interval specified as 1 second
newTimer.Interval = TimeSpan.FromSeconds(1);
// Sub-routine OnTimerTick will be called at every 1 second
newTimer.Tick += OnTimerTick;
// starting the timer
newTimer.Start();
}
}
}

Building and Running

The application is now ready to be built (Ctrl+Shift+B) and ran (Ctrl+F5) either on the emulator or a device.

Note

This application has been tested on the emulator, and should work on a physical device.

This page was last modified on 16 July 2013, at 10:01.
1180 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×