using System; using System.Linq; using System.Threading.Tasks; using System.Windows; using ModernWpf.Controls; using Prism.Common; using Prism.Ioc; using Prism.Services.Dialogs; namespace Dialogs { /// /// Implements to show modal and non-modal dialogs. /// /// /// The dialog's ViewModel must implement IDialogAware. /// public class DialogService : IDialogService { private readonly IContainerExtension _containerExtension; /// /// Initializes a new instance of the class. /// /// public DialogService(IContainerExtension containerExtension) { _containerExtension = containerExtension; } /// /// Shows a non-modal dialog. /// /// The name of the dialog to show. /// The parameters to pass to the dialog. /// The action to perform when the dialog is closed. public void Show(string name, IDialogParameters parameters, Action callback) { throw new NotImplementedException(); } /// /// Shows a non-modal dialog. /// /// The name of the dialog to show. /// The parameters to pass to the dialog. /// The action to perform when the dialog is closed. /// The name of the hosting window registered with the IContainerRegistry. public void Show(string name, IDialogParameters parameters, Action callback, string windowName) { throw new NotImplementedException(); } /// /// Shows a modal dialog. /// /// The name of the dialog to show. /// The parameters to pass to the dialog. /// The action to perform when the dialog is closed. public void ShowDialog(string name, IDialogParameters parameters, Action callback) { ShowDialogInternal(name, parameters, callback, null); } /// /// Shows a modal dialog. /// /// The name of the dialog to show. /// The parameters to pass to the dialog. /// The action to perform when the dialog is closed. /// The name of the hosting window registered with the IContainerRegistry. public void ShowDialog(string name, IDialogParameters parameters, Action callback, string windowName) { ShowDialogInternal(name, parameters, callback, windowName); } void ShowDialogInternal(string name, IDialogParameters parameters, Action callback, string windowName) { var content = _containerExtension.Resolve(name); if (!(content is ContentDialog contentDialog)) throw new NullReferenceException("A dialog's content must be a content dialog"); if (!(contentDialog.DataContext is IDialogAware viewModel)) throw new NullReferenceException("A dialog's ViewModel must implement the IDialogAware interface"); MvvmHelpers.ViewAndViewModelAction(viewModel, d => d.OnDialogOpened(parameters)); Action closeHandler = default; closeHandler += e => { viewModel.RequestClose -= closeHandler; callback?.Invoke(e); }; viewModel.RequestClose += closeHandler; if (contentDialog.Owner == null) contentDialog.Owner = Application.Current?.Windows.OfType().FirstOrDefault(x => x.IsActive); contentDialog.ShowAsync().Await(); } } }