WPF—DispatcherTimer

作者:追风剑情 发布于:2019-8-20 21:55 分类:C#

示例

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.Windows.Threading;//DispatcherTimer
  15.  
  16. namespace WpfApp6
  17. {
  18. /// <summary>
  19. /// MainWindow.xaml 的交互逻辑
  20. /// </summary>
  21. public partial class MainWindow : Window
  22. {
  23. //WPF专用Timer
  24. private DispatcherTimer timer;
  25.  
  26. public MainWindow()
  27. {
  28. InitializeComponent();
  29.  
  30. timer = new DispatcherTimer();
  31. timer.Tick += new EventHandler(OnTick);
  32. timer.Interval = new TimeSpan(0, 0, 1);
  33. }
  34.  
  35. private void Button_Click(object sender, RoutedEventArgs e)
  36. {
  37. //判断timer是否已启动
  38. if (!timer.IsEnabled)
  39. {
  40. timer.Start();
  41. }
  42. }
  43.  
  44. private void OnTick(object sender, EventArgs e)
  45. {
  46. Console.WriteLine("Second: {0}", DateTime.Now.Second);
  47. //DispatcherTimer的回调函数里可访问UI元素
  48. textBlock.Text = DateTime.Now.Second.ToString();
  49. }
  50.  
  51. // 窗口关闭事件
  52. private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  53. {
  54. if (timer != null)
  55. timer.Stop();
  56. }
  57. }
  58. }

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号