FlipClock.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Threading;
  6. namespace HandyControl.Controls;
  7. public class FlipClock : Control
  8. {
  9. private readonly DispatcherTimer _dispatcherTimer;
  10. private bool _isDisposed;
  11. public static readonly DependencyProperty NumberListProperty = DependencyProperty.Register(
  12. nameof(NumberList), typeof(List<int>), typeof(FlipClock), new PropertyMetadata(new List<int> { 0, 0, 0, 0, 0, 0 }));
  13. public List<int> NumberList
  14. {
  15. get => (List<int>) GetValue(NumberListProperty);
  16. set => SetValue(NumberListProperty, value);
  17. }
  18. public static readonly DependencyProperty DisplayTimeProperty = DependencyProperty.Register(
  19. nameof(DisplayTime), typeof(DateTime), typeof(FlipClock), new PropertyMetadata(default(DateTime), OnDisplayTimeChanged));
  20. private static void OnDisplayTimeChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
  21. {
  22. var ctl = (FlipClock) s;
  23. var v = (DateTime) e.NewValue;
  24. ctl.NumberList = new List<int>
  25. {
  26. v.Hour / 10,
  27. v.Hour % 10,
  28. v.Minute / 10,
  29. v.Minute % 10,
  30. v.Second / 10,
  31. v.Second % 10
  32. };
  33. }
  34. public DateTime DisplayTime
  35. {
  36. get => (DateTime) GetValue(DisplayTimeProperty);
  37. set => SetValue(DisplayTimeProperty, value);
  38. }
  39. public FlipClock()
  40. {
  41. _dispatcherTimer = new DispatcherTimer(DispatcherPriority.Render)
  42. {
  43. Interval = TimeSpan.FromMilliseconds(200)
  44. };
  45. IsVisibleChanged += FlipClock_IsVisibleChanged;
  46. }
  47. ~FlipClock() => Dispose();
  48. public void Dispose()
  49. {
  50. if (_isDisposed) return;
  51. IsVisibleChanged -= FlipClock_IsVisibleChanged;
  52. _dispatcherTimer.Stop();
  53. _isDisposed = true;
  54. GC.SuppressFinalize(this);
  55. }
  56. private void FlipClock_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  57. {
  58. if (IsVisible)
  59. {
  60. _dispatcherTimer.Tick += DispatcherTimer_Tick;
  61. _dispatcherTimer.Start();
  62. }
  63. else
  64. {
  65. _dispatcherTimer.Stop();
  66. _dispatcherTimer.Tick -= DispatcherTimer_Tick;
  67. }
  68. }
  69. private void DispatcherTimer_Tick(object sender, EventArgs e) => DisplayTime = DateTime.Now;
  70. }