I'm implementing a countdown in my app
private async void Window_Activated(object sender, WindowActivatedEventArgs args)
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,1,0);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, object e)
{
TimeSpan timeSpan = new TimeSpan(blockTime.Hours, blockTime.Minutes, blockTime.Seconds);
if (timeSpan != TimeSpan.Zero)
{
timeSpan = timeSpan.Subtract(TimeSpan.FromMinutes(1));
Countdown_TexBlock.Text = String.Format("{0}:{1}", timeSpan.Hours, timeSpan.Minutes);
dispatcherTimer.Start();
}
else
{
dispatcherTimer.Stop();
}
}
The code works but only one time For example I put 15 minutes in the blocktime (the time that the countdown will be running) after a minute the countdown.text would be 0:14. So only works after the first minute
Is not supposed to be restarted with dispatcher.start()
In the code that you posted, I don't see the
blockTimevariable being changed to any other value than it has in the beginning. This means that on every tick ofdispatchTimerthe value of thetimeSpan.Subtractexpression will always evaluate to the same 14 minutes. In your code, that 14 minutes is assigned to a local vaiable that is disposed when the tick is over. This gives the appearance that thedispatchTimerhas stopped issuingTickwhen it hasn't.Here's what I ran that works as expected (for testing, I changed the minutes to seconds to make it observable in a reasonable time).