我正在尝试使用一个新的IDialogService,它在Github的问题1666. A New IDialogService for WPF中被讨论。我喜欢这个新功能,但是我无法找到一种解决使用IDialogService与InteractionRequest进行比较的情况的方法。
有一个按钮,按下该按钮会打开非模态对话框。 如果用户在对话框仍然打开时再次按下相同的按钮,则对话框将关闭。 应该如何以适当的方式实现这种行为?
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的名称。
Show
还是ShowDialog
?我期望后者会等待(你仍然可以从另一个线程引发事件),但Show
不应该阻塞。 - Haukinger