Stop Watch using Windows Phone
This article explains how to create stop watch in Windows Phone 7. It extends the article: Implement Timer control in Windows Phone.
Article Metadata
Code Example
Source file: Media:StopWatch.zip
Tested with
Devices(s): Windows Phone Emulator
Compatibility
Platform(s): Windows Phone 7.5
Article
Keywords: DispatcherTimer , Stop watch
Created: girishpadia
(13 Oct 2011)
Last edited: hamishwillee
(30 Nov 2012)
Introduction
This code example creates a simple stop watch which you can start and stop using the buttons Start Clock and Stop respectively. The example uses DispatcherTimer to update the stopwatch every second and lists how long the timer ran (calculated from current DateTime when the buttons are pressed).
Implementation
- Create a new "Silverlight" project using C# and name the project as "StopWatch".
- Drag one textblock from the toolbox and name it txtClock
- Drag two buttons and place them just below the txtClock as shown in the application image below. Name the buttons btnStart and btnStop respectively.
- In the XAML file, add the event handlers for the newly created buttons by adding the attribute in the btnStart tag and
Click="btnStart_Click"
in the btnStop tag. Alternatively, just double click both buttons in the layout view.Click="btnStop_Click"
- Drag another textblock and name it lblTimer and place it below the buttons.
- Copy and paste following code into your application.
using System;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
namespace StopWatch
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
DateTime lastTime,startTime;
public MainPage()
{
InitializeComponent();
}
void OnTimerTick(Object sender, EventArgs args)
{
txtClock.Text = DateTime.Now.ToString();
}
private void btnStart_Click(object sender, System.Windows.RoutedEventArgs e)
{
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
newTimer.Tick += OnTimerTick;
newTimer.Start();
lastTime = DateTime.Now;
startTime = DateTime.Now;
lblTimer.Text = "Start time : " + lastTime.ToString() + "\n";
}
private void btnStop_Click(object sender, System.Windows.RoutedEventArgs e)
{
DateTime endTime = DateTime.Now;
TimeSpan span = endTime.Subtract(startTime);
lblTimer.Text += "Seconds from begining: "+span.TotalSeconds.ToString()+"\n";
span = endTime.Subtract(lastTime);
lblTimer.Text += "Seconds from last stop: " + span.TotalSeconds.ToString() + "\n\n";
lastTime = DateTime.Now;
}
}
}
Tested On
The application is tested on Windows Phone Emulator.


