Namespaces
Variants
Actions

Implement timers in Windows Phone

Jump to: navigation, search

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

SignpostIcon Code 52.png
Article Metadata

Tested with
Devices(s): Windows Phone Emulator

Compatibility
Platform(s): Windows Phone 7.5, 8

Article
Keywords: dispatchertimer, windows phone
Created: girishpadia (13 Oct 2011)
Last edited: hamishwillee (10 Apr 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 10 April 2013, at 04:28.
1367 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved