Add the "ShowAsync<T>():T" method and IDialogResult interface to the Dialog control.

This commit is contained in:
DingpingZhang committed 2019-04-02 10:31:26 +08:00
1 parent b7c87f8ab2
commit 82e9577a9f
1 file changed
+54 -2
+54 -2
View File
@@ -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<TResult> ShowAsync<TView, TResult>() where TView : class, new() =>
ShowAsync<TResult>(new TView());
public static Task<TResult> ShowAsync<TResult>(object content)
{
var tcs = new TaskCompletionSource<TResult>();
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<T>() 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);
}
}
}
}
}
}