WaitingSpinner.xaml.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Shapes;
  5. using System.Windows.Threading;
  6. namespace DocTools.WPF
  7. {
  8. /// <summary>
  9. /// WaitingSpinner.xaml 的交互逻辑
  10. /// </summary>
  11. public partial class WaitingSpinner : UserControl
  12. {
  13. #region Private Variables
  14. private readonly DispatcherTimer _animationTimer;
  15. #endregion Private Variables
  16. #region Constructor
  17. public WaitingSpinner()
  18. {
  19. InitializeComponent();
  20. // 每40 ms 转一下
  21. _animationTimer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher) { Interval = new TimeSpan(0, 0, 0, 0, 80) };
  22. Visibility = Visibility.Collapsed;
  23. }
  24. #endregion Constructor
  25. private void Start()
  26. {
  27. _animationTimer.Tick += HandleAnimationTick;
  28. _animationTimer.Start();
  29. }
  30. private void Stop()
  31. {
  32. _animationTimer.Stop();
  33. _animationTimer.Tick -= HandleAnimationTick;
  34. }
  35. private void HandleAnimationTick(object sender, EventArgs e)
  36. {
  37. SpinnerRotate.Angle = (SpinnerRotate.Angle + 36) % 360;
  38. }
  39. private void OnCanvasLoaded(object sender, RoutedEventArgs e)
  40. {
  41. SpinnerRotate.CenterX = (float)0.5 * CanvasSpinner.Width;
  42. SpinnerRotate.CenterY = (float)0.5 * CanvasSpinner.Height;
  43. const double offset = Math.PI;
  44. const double step = Math.PI * 2 / 10.0;
  45. SetPosition(C0, offset, 0.0, step);
  46. SetPosition(C1, offset, 1.0, step);
  47. SetPosition(C2, offset, 2.0, step);
  48. SetPosition(C3, offset, 3.0, step);
  49. SetPosition(C4, offset, 4.0, step);
  50. SetPosition(C5, offset, 5.0, step);
  51. SetPosition(C6, offset, 6.0, step);
  52. SetPosition(C7, offset, 7.0, step);
  53. SetPosition(C8, offset, 8.0, step);
  54. }
  55. private void SetPosition(Ellipse ellipse, double offset, double posOffSet, double step)
  56. {
  57. ellipse.SetValue(Canvas.LeftProperty, CanvasSpinner.Width * 0.5 + Math.Sin(offset + posOffSet * step) * CanvasSpinner.Width * 0.4 - 0.5 * ellipse.Width);
  58. ellipse.SetValue(Canvas.TopProperty, CanvasSpinner.Width * 0.5 + Math.Cos(offset + posOffSet * step) * CanvasSpinner.Width * 0.4 - 0.5 * ellipse.Width);
  59. }
  60. private void OnCanvasUnLoaded(object sender, RoutedEventArgs e)
  61. {
  62. Stop();
  63. }
  64. /// <summary>
  65. /// Start the waiting animation
  66. /// </summary>
  67. public void StartWaiting()
  68. {
  69. Visibility = Visibility.Visible;
  70. Start();
  71. }
  72. /// <summary>
  73. /// Stop the waiting animation
  74. /// </summary>
  75. public void StopWaiting()
  76. {
  77. Stop();
  78. Visibility = Visibility.Collapsed;
  79. }
  80. }
  81. }