为 Windows Phone 秒表计时器创建暂停按钮

本文关键字:创建 暂停 按钮 计时器 Windows Phone | 更新日期: 2023-09-27 18:30:34

我已经创建了停止和开始按钮,但无法创建暂停/恢复按钮。有人可以给我一些关于如何处理这些方法的提示/代码吗?

PS:我的代码的另一个问题是它的计时器增加了 1000 而不是 1!有什么线索吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
namespace PhoneApp2
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        DispatcherTimer newTimer = new DispatcherTimer();
        int time;
        DateTime currentTime= new DateTime();
        public MainPage()
        {
            InitializeComponent();
        }

        void OnTimerTick(object sender, EventArgs args)
        {
            long elapseTime = DateTime.Now.Ticks - currentTime.Ticks;
            TimeSpan elapsedSpan = new TimeSpan(elapseTime);
            textClock.Text = elapsedSpan.TotalMilliseconds.ToString("0.00");
        }
        private void Button_Stop(object sender, RoutedEventArgs e)
        {
            newTimer.Stop();
        }
        private void Button_Pause(object sender, RoutedEventArgs e)
        {
            //newTimer.Stop(); ??
         }
        private void Button_Start(object sender, RoutedEventArgs e)
        {
            currentTime = DateTime.Now;
            newTimer.Interval = TimeSpan.FromSeconds(1);
            newTimer.Tick += OnTimerTick;
            newTimer.Start();

        }

    }
}

为 Windows Phone 秒表计时器创建暂停按钮

实现它的方法很少。第一个是使用秒表类来测量时间。

public partial class MainPage
  : PhoneApplicationPage
{
    Stopwatch sw = new Stopwatch();
    DispatcherTimer newTimer = new DispatcherTimer();
    public MainPage()
    {
        InitializeComponent();
        newTimer.Interval = TimeSpan.FromMilliseconds(1000 / 30);
        newTimer.Tick += OnTimerTick;
    }
    void OnTimerTick(object sender, EventArgs args)
    {
        UpdateUI();
    }
    private void Button_Stop(object sender, RoutedEventArgs e)
    {
        Stop();
    }
    private void Button_Pause(object sender, RoutedEventArgs e)
    {
        Pause();
    }
    private void Button_Start(object sender, RoutedEventArgs e)
    {
        Start();
    }
    void UpdateUI()
    {
        textClock.Text = sw.ElapsedMilliseconds.ToString("0.00");
    }
    void Start()
    {
        sw.Reset();
        sw.Start();
        newTimer.Start();
        UpdateUI();
    }
    void Stop()
    {
        sw.Stop();
        newTimer.Stop();
        UpdateUI();
    }
    void Pause()
    {
        Stop();
    }
    void Resume()
    {
         sw.Start();
         newTimer.Start();
         UpdateUI();
    }
}