WPF 實現倒計時


效果:

UI:放置一個Label ---><Label Name="lblSecond" FontSize="20" Foreground="Red" ></Label>

CS:

  private int countSecond=300; //記錄秒數

  private void UserControl_Loaded(object sender, RoutedEventArgs e)

  {

    private DispatcherTimer disTimer = new DispatcherTimer();

    disTimer.Interval = new TimeSpan(0, 0, 0, 1); //參數分別為:天,小時,分,秒。此方法有重載,可根據實際情況調用。

    disTimer.Tick += new EventHandler(disTimer_Tick); //每一秒執行的方法

    disTimer.Start();

  }

  void disTimer_Tick(object sender, EventArgs e)

  {

    if(countSecond==0)

    {

      MessageBox.Show("結束");

    }

    else

    {

      //判斷lblSecond是否處於UI線程上

      if (lblSecond.Dispatcher.CheckAccess())

      {

        lblSecond.Content=countSecnd.ToString();

      }

      else

      {

        lblSecond.Dispatcher.BeginInvoke(DispatcherPriority.Normal,(Action)(() =>{

          lblSecond.Content=countSecond.ToString();

        }));  

      }

      countSecond--;

    }

  }

  

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM