DialogExtension.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Threading.Tasks;
  3. using System.Windows;
  4. using HandyControl.Controls;
  5. namespace HandyControl.Tools.Extension;
  6. public interface IDialogResultable<T>
  7. {
  8. T Result { get; set; }
  9. Action CloseAction { get; set; }
  10. }
  11. public static class DialogExtension
  12. {
  13. public static Task<TResult> GetResultAsync<TResult>(this Dialog dialog)
  14. {
  15. var tcs = new TaskCompletionSource<TResult>();
  16. try
  17. {
  18. if (dialog.IsClosed)
  19. {
  20. SetResult();
  21. }
  22. else
  23. {
  24. dialog.Unloaded += OnUnloaded;
  25. dialog.GetViewModel<IDialogResultable<TResult>>().CloseAction = dialog.Close;
  26. }
  27. }
  28. catch (Exception e)
  29. {
  30. tcs.TrySetException(e);
  31. }
  32. return tcs.Task;
  33. // ReSharper disable once ImplicitlyCapturedClosure
  34. void OnUnloaded(object sender, RoutedEventArgs args)
  35. {
  36. dialog.Unloaded -= OnUnloaded;
  37. SetResult();
  38. }
  39. void SetResult()
  40. {
  41. try
  42. {
  43. tcs.TrySetResult(dialog.GetViewModel<IDialogResultable<TResult>>().Result);
  44. }
  45. catch (Exception e)
  46. {
  47. tcs.TrySetException(e);
  48. }
  49. }
  50. }
  51. public static Dialog Initialize<TViewModel>(this Dialog dialog, Action<TViewModel> configure)
  52. {
  53. configure?.Invoke(dialog.GetViewModel<TViewModel>());
  54. return dialog;
  55. }
  56. public static TViewModel GetViewModel<TViewModel>(this Dialog dialog)
  57. {
  58. if (!(dialog.Content is FrameworkElement frameworkElement))
  59. throw new InvalidOperationException("The dialog is not a derived class of the FrameworkElement. ");
  60. if (!(frameworkElement.DataContext is TViewModel viewModel))
  61. throw new InvalidOperationException($"The view model of the dialog is not the {typeof(TViewModel)} type or its derived class. ");
  62. return viewModel;
  63. }
  64. }