Jump to content

C# and WPF countdown timer

- - - - -

  • Please log in to reply
1 reply to this topic

#1
Jrb

Jrb

    Learning Programmer

  • Members
  • PipPipPip
  • 49 posts
Hi all.

I'm trying to make a C#/WPF app with a date countdown. The problem I'm having is I'm trying to use the t.days, t.minutes, t.seconds variables in textblocks and then use a timer to count them down. I just have no idea on how to implement this.

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Windows.Threading;


namespace WpfApplication2

{


	public partial class MainWindow : Window

	{

		private int _time;

    	        private DispatcherTimer _countdownTimer;

		

		public MainWindow()

		{

			this.InitializeComponent();

			DateTime eventTime = DateTime.Parse("1/20/2012 12:00:01 AM");

                        DateTime startDate = DateTime.Now;

                        TimeSpan t = eventTime - startDate;

                        string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", t.Days, t.Hours, t.Minutes, t.Seconds);

			

		         _countdownTimer = new DispatcherTimer();

        	         _countdownTimer.Interval = new TimeSpan(0,0,1);

        	         _countdownTimer.Tick += new EventHandler(CountdownTimerStep);

		         _countdownTimer.Start();

		}

	}

}

Basically what I'm trying to do: I have three textblocks. One for days, one for minutes, and one for seconds. I want to use the timer to countdown the days, minutes, and seconds in a live format. Obviously when the seconds reach zero it'll have to subtract 1 from the minute textblock and reset the seconds textblock. Same for the others.

Anyone have any ideas or previously used code?

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Could be done with some simple if statements. After subtracting one from the seconds value, you check:


if seconds < 0:

  add 60 to seconds

  subtract 1 from minutes


You would then do the same thing for the minutes, and finally for the hours, each time adding an appropriate amount to the value and subtracting one from the next.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users