2018/10/17

[C#] WPF Timer

WPF有很多種計時器可以用來跑動畫的東西,這裡寫一個比較簡單的Timer用法。
這種寫法是直接寫在cs檔裡面,用DispatcherTimer來設定一個每秒count+1的計時器,並且加到5之後就停下來。


cs程式碼:
  1. private int count = 0;
  2. private DispatcherTimer timer;
  3.  
  4. public MainWindow()
  5. {
  6. InitializeComponent();
  7.  
  8. // set timer
  9. timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
  10. timer.Tick += TimerTick;
  11. timer.Start();
  12. }
  13.  
  14. private void TimerTick(object sender, EventArgs e)
  15. {
  16. count++;
  17. if(count == 5)
  18. {
  19. timer.Stop();
  20. }
  21. }

End

沒有留言:

張貼留言