diff --git a/HandyControl/Controls/Other/Dialog.cs b/HandyControl/Controls/Other/Dialog.cs index a5f18d03..cdd81695 100644 --- a/HandyControl/Controls/Other/Dialog.cs +++ b/HandyControl/Controls/Other/Dialog.cs @@ -1,4 +1,7 @@ -using System.Windows.Controls; +using System; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using HandyControl.Interactivity; @@ -6,6 +9,11 @@ using HandyControl.Tools; namespace HandyControl.Controls { + public interface IDialogResult + { + object Result { get; set; } + } + public class Dialog : ContentControl { private Adorner _container; @@ -15,6 +23,50 @@ namespace HandyControl.Controls CommandBindings.Add(new CommandBinding(ControlCommands.Close, (s, e) => Close())); } + public static Task ShowAsync() where TView : class, new() => + ShowAsync(new TView()); + + public static Task ShowAsync(object content) + { + var tcs = new TaskCompletionSource(); + + var dialog = Show(content); + dialog.Unloaded += OnUnloaded; + + return tcs.Task; + + void OnUnloaded(object sender, RoutedEventArgs args) + { + try + { + dialog.Unloaded -= OnUnloaded; + tcs.SetResult(GetResult(dialog)); + } + catch (Exception e) + { + tcs.SetException(e); + } + } + + TResult GetResult(Dialog embeddedDialog) + { + if (!(embeddedDialog.Content is FrameworkElement frameworkElement)) + throw new InvalidOperationException("The dialog is not a derived class of the FrameworkElement. "); + + if (!(frameworkElement.DataContext is IDialogResult dialogResult)) + throw new InvalidOperationException("The view model of the dialog is not implement the IDialogResult interface. "); + + if (!(dialogResult.Result is TResult result)) + throw new InvalidCastException("Could not cast " + + $"the {(dialogResult.Result != null ? $"{dialogResult.Result.GetType()} type" : "null value")} " + + $"to the {typeof(TResult)} type. "); + + return result; + } + } + + public static Dialog Show() where T : class, new() => Show(new T()); + public static Dialog Show(object content) { var dialog = new Dialog @@ -64,6 +116,6 @@ namespace HandyControl.Controls layer?.Remove(_container); } } - } + } } } \ No newline at end of file