MVVM, DialogService and Dialog Result

本文关键字:Dialog Result and DialogService MVVM | 更新日期: 2023-09-27 18:21:24

我目前正在学习WPF/MVVM,并一直在使用以下问题中的代码使用对话框服务显示对话框(包括Julian Dominguez的布尔值更改):

使用MVVM在wpf中进行对话的好方法还是坏方法?

显示对话框效果很好,但对话框结果总是错误的,尽管实际上显示的是对话框。我的DialogViewModel当前为空,我想也许我需要将我的DialogView模型"连接"到RequestCloseDialog事件。是这样吗?

MVVM, DialogService and Dialog Result

您的DialogViewmodel是否实现IDialogResultVMHelper?您的View/DataTemplate是否有一个到DialogView模型的命令绑定,从而引发RequestCloseDialog?

例如

public class DialogViewmodel : INPCBase, IDialogResultVMHelper
{
    private readonly Lazy<DelegateCommand> _acceptCommand;
    public DialogViewmodel()
    {
        this._acceptCommand = new Lazy<DelegateCommand>(() => new DelegateCommand(() => InvokeRequestCloseDialog(new RequestCloseDialogEventArgs(true)), () => **Your Condition goes here**));
    }
    public event EventHandler<RequestCloseDialogEventArgs> RequestCloseDialog;
    private void InvokeRequestCloseDialog(RequestCloseDialogEventArgs e)
    {
        var handler = RequestCloseDialog;
        if (handler != null) 
            handler(this, e);
    }
}

对话框控件中的任何位置:

<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" MinHeight="30">
    <Button IsDefault="True" Content="Übernehmen" MinWidth="100" Command="{Binding AcceptCommand}"/>
    <Button IsCancel="True" Content="Abbrechen" MinWidth="100"/>
</StackPanel>

然后你的结果应该在你的视图模型中工作

var dialog = new DialogViewmodel();
var result = _dialogservice.ShowDialog("My Dialog", dialog );
if(result.HasValue && result.Value)
{
    //accept true
}
else
{
    //Cancel or false
}