MVVM,DialogService和Dialog结果

时间:2014-09-11 05:26:06

标签: c# wpf mvvm dialog modal-dialog

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

Good or bad practice for Dialogs in wpf with MVVM?

显示对话框效果很好,但是尽管实际显示了对话框,但对话框结果始终为false。我的DialogViewModel目前是空的,我想也许我需要"挂钩"我的DialogViewModel到RequestCloseDialog事件。是这种情况吗?

1 个答案:

答案 0 :(得分:1)

您的DialogViewmodel是否实现了IDialogResultVMHelper?你的View / DataTemplate是否有一个命令绑定到DialogViewmodel,它引发了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);
    }
}

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

然后您的结果应该在您的viewmodel中运行

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

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