Progress.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.ComponentModel;
  3. using System.Linq;
  4. using System.Windows.Media.Imaging;
  5. namespace InABox.WPF
  6. {
  7. public class ProgressSection
  8. {
  9. public ProgressSection(string message, Action action)
  10. {
  11. Message = message;
  12. Action = action;
  13. }
  14. public string Message { get; set; }
  15. public Action Action { get; set; }
  16. }
  17. public static class Progress
  18. {
  19. private static ProgressForm form;
  20. public static BitmapImage DisplayImage { get; set; }
  21. public static bool IsVisible => form != null;
  22. public static string Message => form?.GetMessage();
  23. public static void ShowModal(params ProgressSection[] sections)
  24. {
  25. if (!sections.Any())
  26. return;
  27. var progress = new ProgressForm();
  28. progress.DisplayImage = DisplayImage;
  29. progress.Activated += (_, args) =>
  30. {
  31. progress.Dispatcher.Invoke(() =>
  32. {
  33. foreach (var section in sections)
  34. {
  35. progress.Progress.Content = section.Message;
  36. section.Action();
  37. }
  38. progress.Close();
  39. });
  40. };
  41. progress.ShowActivated = true;
  42. progress.ShowDialog();
  43. }
  44. public static void ShowModal(string message, Action<IProgress<string>> work)
  45. {
  46. var progress = new ProgressForm();
  47. progress.DisplayImage = DisplayImage;
  48. progress.Progress.Content = message;
  49. progress.Loaded += (_, args) =>
  50. {
  51. var worker = new BackgroundWorker();
  52. var update = new Progress<string>(data => progress.Progress.Content = data);
  53. worker.DoWork += (o, e) => work(update);
  54. worker.RunWorkerCompleted +=
  55. (o, e) => progress.Close();
  56. worker.RunWorkerAsync();
  57. };
  58. progress.ShowDialog();
  59. }
  60. public static void Show(string message)
  61. {
  62. if (form == null)
  63. {
  64. form = new ProgressForm();
  65. form.DisplayImage = DisplayImage;
  66. form.Show();
  67. }
  68. form.UpdateWindow(message);
  69. }
  70. public static void SetMessage(string message)
  71. {
  72. form.UpdateWindow(message);
  73. }
  74. public static void Close()
  75. {
  76. form?.CloseWindow();
  77. form = null;
  78. }
  79. }
  80. }