wpf MVVM、DialogService 和 Dialog Result

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25779674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:31:07  来源:igfitidea点击:

MVVM, DialogService and Dialog Result

c#wpfmvvmdialogmodal-dialog

提问by bdan

I'm currently learning WPF/MVVM, and have been using the code in the following question to display dialogs using a Dialog Service (including the boolean change from Julian Dominguez):

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

Good or bad practice for Dialogs in wpf with MVVM?

使用 MVVM 在 wpf 中进行对话的好坏做法?

Displaying a dialog works well, but the dialog result is always false despite the fact that the dialog is actually being shown. My DialogViewModel is currently empty, and I think that maybe I need to "hook up" my DialogViewModel to the RequestCloseDialog event. Is this the case?

显示对话框效果很好,但尽管实际上正在显示对话框,但对话框结果始终为假。我的 DialogViewModel 目前是空的,我想我可能需要将我的 DialogViewModel 与 RequestCloseDialog 事件“挂钩”。是这种情况吗?

采纳答案by blindmeis

does your DialogViewmodel implement IDialogResultVMHelper? and does your View/DataTemplate has a Command Binding to your DialogViewmodel which raise the RequestCloseDialog?

您的 DialogViewmodel 是否实现了 IDialogResultVMHelper?你的视图/数据模板是否有一个命令绑定到你的 DialogViewmodel,它引发了 RequestCloseDialog?

eg

例如

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);
    }
}

anywhere in your Dialog control:

在 Dialog 控件中的任何位置:

<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>

and then your result should work in your viewmodel

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

var dialog = new DialogViewmodel();
var result = _dialogservice.ShowDialog("My Dialog", dialog );

if(result.HasValue && result.Value)
{
    //accept true
}
else
{
    //Cancel or false
}