如何在Windows Phone 7.1上添加计时器?

时间:2013-01-16 11:13:19

标签: c# windows-phone-7.1

我正在寻找一种方法来添加一个计时器(或秒表),它将在应用程序启动或点击按钮时从0开始计数,并在用户浏览不同页面后继续计数,然后能够显示在应用程序的最后一页中经过了多少时间。我一直在讨论DispatcherTimer课程,但说实话,我很难理解它。任何帮助,甚至是朝着正确方向点头的人都将不胜感激!

2 个答案:

答案 0 :(得分:1)

您只需存储应用启动时间,然后从存储值中减去当前时间。

在App.cs存储中启动应用程序的时间:

    private static DateTime _starttime = DateTime.Now;

    public static DateTime StartTime
    {
        get
        {
            return _starttime;
        }
    }

在您的页面或您需要获取应用程序运行的当前时间的任何位置,您只需从存储的时间中减去当前时间。我在按钮点击处理程序中使用它,见下文:

    private void timebutton_Click(object sender, RoutedEventArgs e)
    {
        TimeSpan time = (DateTime.Now - App.StartTime);

        this.timenow.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
    }

答案 1 :(得分:1)

如果您想使用时间,可以在显示时间的页面上添加一个!

将此代码添加到构造函数或要激活计时器的其他位置。 (App.StartTime与我在其他答案中写的相同)

        DispatcherTimer timer = new DispatcherTimer();

        timer.Tick +=
            delegate(object s, EventArgs args)
            {
                TimeSpan time = (DateTime.Now - App.StartTime);

                this.timenow.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
            };

        timer.Interval = new TimeSpan(0, 0, 1); // one second
        timer.Start();