Prism。关闭使用IDialogService创建的对话框

问题描述 投票:1回答:1

我正在尝试使用在github问题1666. A New IDialogService for WPF中讨论的新IDialogService。我喜欢这项新功能,但找不到与InteractionRequest相比使用IDialogService的一种解决方案。

有一个按钮,按此按钮将打开非模式对话框。如果用户再次按下同一按钮,而对话框仍然打开,则对话框关闭。应该如何以正确的方式实现此行为?

MainWindowViewModel

public class MainWindowViewModel : BindableBase
{
    private readonly IDialogService _dialogService;
    public DelegateCommand CustomPopupCommand { get; }

    public MainWindowViewModel(IDialogService dialogService)
    {
        _dialogService = dialogService;
        CustomPopupCommand = new DelegateCommand(OpenClosePopup);
    }

    private void OpenClosePopup()
    {
        // It looks like some additional logic should be implemented here.
        // How to save previously opened IDialogAware instance and close it if needed?
        _dialogService.Show("CustomPopupView", new DialogParameters("Title=Good Title"), result => { });
    }
}

CustomPopupViewModel

public class CustomPopupViewModel : BindableBase, IDialogAware
{
    private string _title;
    public string Title
    {
        get => _title;
        set => SetProperty(ref _title, value);
    }
    public DelegateCommand<object> CloseCommand { get; }

    public CustomPopupViewModel()
    {
        CloseCommand = new DelegateCommand<object>(CloseDialog);
    }

    public event Action<IDialogResult> RequestClose;

    public void OnDialogOpened(IDialogParameters parameters)
    {
        Title = parameters.GetValue<string>(nameof(Title));
    }

    public void OnDialogClosed()
    {
    }

    public bool CanCloseDialog()
    {
        return true;
    }

    public void RaiseRequestClose(IDialogResult dialogResult)
    {
        RequestClose?.Invoke(dialogResult);
    }

    private void CloseDialog(object button)
    {
        RaiseRequestClose(
            new DialogResult(button is ButtonResult buttonResult ? buttonResult : ButtonResult.Cancel));
    }
}

我不知道如何以正确的方式实现它,因为方法IDialogService.Show()与了解ViewModel和View完全脱钩了。当然除了View的名称。

c# wpf mvvm prism
1个回答
1
投票

您总是可以通过事件聚合器发送事件,如果一次打开多个对话框,可能必须在对话框参数中传递一些ID才能关闭正确的对话框。

但是感觉确实很笨拙,我更希望从IDisposable / Show中获得一个ShowDialog,以关闭Dispose上的对话框。

public CustomPopupViewModel(IEventAggregator eventAggregator)
{
    eventAggregator.GetEvent<CloseDialogEvent>().Subscribe( id => { if (id == _id) CloseMe(); } );
}

public void OnDialogOpened(IDialogParameters parameters)
{
    _id = parameters.GetValue<string>("id");
}

_dialogService.Show("CustomPopupView", new DialogParameters("id=12345"), result => { });

_eventAggregator.GetEvent<CloseDialogEvent>().Publish("12345");
© www.soinside.com 2019 - 2024. All rights reserved.