Skip to content

Instantly share code, notes, and snippets.

@jchadwick
Created March 7, 2013 03:28
Show Gist options
  • Save jchadwick/5105385 to your computer and use it in GitHub Desktop.
Save jchadwick/5105385 to your computer and use it in GitHub Desktop.
WPF Countdown Timer
<Window x:Class="StoryboardDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock x:Name="CountdownDisplay" FontFamily="Calibri" FontSize="60"/>
</Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace StoryboardDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MouseDoubleClick += (o, args) => StartCountdown(CountdownDisplay);
}
private void StartCountdown(FrameworkElement target)
{
var countdownAnimation = new StringAnimationUsingKeyFrames();
for (var i = 5; i > 0; i--)
{
var keyTime = TimeSpan.FromSeconds(5 - i);
var frame = new DiscreteStringKeyFrame(i.ToString(), KeyTime.FromTimeSpan(keyTime));
countdownAnimation.KeyFrames.Add(frame);
}
countdownAnimation.KeyFrames.Add(new DiscreteStringKeyFrame(" ", KeyTime.FromTimeSpan(TimeSpan.FromSeconds(6))));
Storyboard.SetTargetName(countdownAnimation, target.Name);
Storyboard.SetTargetProperty(countdownAnimation, new PropertyPath(TextBlock.TextProperty));
var countdownStoryboard = new Storyboard();
countdownStoryboard.Children.Add(countdownAnimation);
countdownStoryboard.Completed += CountdownTimer_Completed;
countdownStoryboard.Begin(this);
}
private void CountdownTimer_Completed(object sender, EventArgs e)
{
MessageBox.Show("Time's up!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment