2013-04-02 57 views
1

我在Windows手機上製作計時器應用程序時遇到問題。 我有文本框設置爲00:00:00,即時嘗試增加它每秒,但在第一秒後,它不會再做。我相信這是一個簡單的解決方案,並會非常感謝任何幫助。謝謝windows phone增加計時器

公衆的MainPage(){ 在InitializeComponent ();

 DispatcherTimer timer = new DispatcherTimer(); 
     timer.Interval = TimeSpan.FromSeconds(1); 
     timer.Tick += OnTimerTick; 
     timer.Start(); 
    } 

    void OnTimerTick(object sender, EventArgs args) 
    { 
     txtTimer.Text = DateTime.Now.ToString(); 
    } 

    private void btnStartClick(object sender, EventArgs e) 
    { 

     DispatcherTimer timer = new DispatcherTimer(); 

     timer.Tick += 
      delegate(object s, EventArgs args) 
      { 
       TimeSpan time = new TimeSpan(0); 
       time += TimeSpan.FromSeconds(1);     
       this.timenow.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds); 
      }; 


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

    } 
+0

歡迎來到StackOverflow。你有沒有試過調試你的代碼? –

回答

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

time的變量創建的每個計時器滴答時間。因此每次添加一秒到零時間跨度。你需要從委託中提取它。通常你會讓它成爲一個班級領域。

+0

感謝您的回覆。所以我必須從代​​表中提取它,所以它會繼續添加一個而不是再次啓動?我將如何去做這件事。對不起,它可能很容易,但我只是開始 – Ryan

+0

只需在課程中添加'TimeSpan time;'(不包括任何函數)。在啓動定時器之前,在'btnStartClick'中添加'time = new TimeSpan(0);'。刪除我複製到答案的代碼的第一行(代表的第一行)。 – Aneri

+0

非常感謝您的回覆,它現在可以完美運作。 – Ryan