Created
March 7, 2013 03:28
-
-
Save jchadwick/5105385 to your computer and use it in GitHub Desktop.
WPF Countdown Timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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