Cancel opening dialog in dialog view model

前端 未结 2 865
小蘑菇
小蘑菇 2021-01-17 03:58

I use Prism 7.2.0. I wonder if it is possible to cancel opening dialog in a view model, which implements IDialogAware in case of invalid parameters. I tried the

2条回答
  •  佛祖请我去吃肉
    2021-01-17 04:27

    I don't have a sufficient reputation to add a comment. The solution from thatguy is good, but I've made some changes for memory optimization.

    I've switched the ConfigureDialogWindowContent and ConfigureDialogWindowEvents methods, because I don't want to have the events registered.

    The check itself I've moved to ConfigureDialogWindowContent method. If It not passed, I return ButtonResult.Abort.

    My validation Interface is called IDialogAwareEx, but can be changed for IDialogParametersValidator from thatguy post

     void ShowDialogInternal(string name, IDialogParameters parameters, Action callback, bool isModal, string windowName = null)
        {
            IDialogWindow dialogWindow = CreateDialogWindow(windowName);
            if (!ConfigureDialogWindowContent(name, dialogWindow, parameters))
            {
                callback?.Invoke(new DialogResult(ButtonResult.Abort));
                return;
            }
            ConfigureDialogWindowEvents(dialogWindow, callback);
    
            if (isModal)
                dialogWindow.ShowDialog();
            else
                dialogWindow.Show();
    
        }
    
     protected virtual bool ConfigureDialogWindowContent(string dialogName, IDialogWindow window, IDialogParameters parameters)
        {
            var content = _containerExtension.Resolve(dialogName);
    
            var dialogContent = content as FrameworkElement;
            if (dialogContent == null)
                throw new NullReferenceException("A dialog's content must be a FrameworkElement");
    
            if (dialogContent.DataContext is IDialogAwareEx dialogAwareEx
                && !dialogAwareEx.CanBeOpened(parameters))
            {
                // opening is not allowed
                return false;
            }
    
            var viewModel = dialogContent.DataContext as IDialogAware;
            /* other codes */
    
            return true;
        }
    
        

    提交回复
    热议问题