robbiestells
robbiestells

Reputation: 275

Xaml C#, UWP Stopwatch delay

I'm trying to make a stopwatch feature for a Windows 10 Universal app. Using DispatcherTimer I've been able to get a working stopwatch in that the seconds will count up to 60, trigger the minute to add 1, and reset to zero. The seconds will continue counting up, but there's a 1 second delay when it resets back to zero. Basically when it hits 60, the seconds resets to 0, it stays on 0 for the next second, and then goes up to 1 the following second. Any ideas what might be causing this? Thanks so much!

public sealed partial class MainPage : Page
{
    DispatcherTimer secondstimer = new DispatcherTimer();
    int secondscount = 0;

    int minutescount = 0;
    int hourscount = 0;

    public MainPage()
    {

        this.InitializeComponent();

        secondstimer.Interval = new TimeSpan(0, 0, 1);
        secondstimer.Tick += Secondstimer_Tick;

        SecondsTextBlock.Text = "00";
        MinutesTextBlock.Text = "00";
        HoursTextBlock.Text = "00";
    }

    private void Secondstimer_Tick(object sender, object e)
    {
        SecondsTextBlock.Text = secondscount++.ToString();

        if (secondscount == 61)
        {
            minutescount++;
            secondscount = 0;

            MinutesTextBlock.Text = minutescount.ToString();
            SecondsTextBlock.Text = secondscount.ToString();

        }
        if (minutescount == 61)
        {
            hourscount++;
            minutescount = 0;
            MinutesTextBlock.Text = minutescount.ToString();
            HoursTextBlock.Text = hourscount.ToString();
        }
    }
}

Upvotes: 1

Views: 2159

Answers (2)

Janekdererste
Janekdererste

Reputation: 11

You could also use the StopWatch class.

https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch%28v=vs.110%29.aspx

var stopWatch = new StopWatch();
stopWatch.Start();

It'll give you the elapsed time like this

HoursTextBlock.Text = stopWatch.Elapsed.Hours.ToString();
MinutesTextBlock.Text = stopWatch.Elapsed.Minutes.ToString();
SecondsTextBlock.Text = stopWatch.Elapsed.Seconds.ToString();

Upvotes: 1

Jon
Jon

Reputation: 2891

You could eliminate the complexity and just continually count the seconds and then set the TextBlocks like this:

HoursTextBlock.Text = (secondscount / 3600).ToString();
MinutesTextBlock.Text = (secondscount % 3600) / 60).ToString();
SecondsTextBlock.Text = (secondscount % 60).ToString();

Or something similar. Hope this helps.

Upvotes: 0

Related Questions