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

时间:2013-09-09 04:34:41

标签: c# visual-studio-2010 windows-phone-7 windows-mobile

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

P.S。:我的代码的另一个问题是它的计时器增加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();


        }



    }
}

1 个答案:

答案 0 :(得分:1)

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

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