Xaml C#、UWP 秒表延迟

Xaml C#, UWP Stopwatch delay

我正在尝试为 Windows 10 通用应用制作秒表功能。使用 DispatcherTimer 我已经能够得到一个工作秒表,因为秒数将计数到 60,触发分钟加 1,然后重置为零。秒数将继续递增,但在重置为零时会有 1 秒的延迟。基本上当它达到 60 时,秒数重置为 0,下一秒保持为 0,然后下一秒上升到 1。任何想法可能是什么原因造成的?非常感谢!

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();
        }
    }
}

您可以消除复杂性,只需不断计算秒数,然后像这样设置 TextBlocks:

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

或类似的东西。希望这有帮助。

您也可以使用秒表 class。

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

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

它会像这样给你经过的时间

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