MVVM: Good way to close dialog and set DialogResult

I was inspired by Thejuan's answer to write a simpler attached property. No styles, no triggers; instead, you can just do this:

<Window ... xmlns:xc="clr-namespace:ExCastle.Wpf" xc:DialogCloser.DialogResult="{Binding DialogResultValue}">

This is almost as clean as if the WPF team had gotten it right and made DialogResult a dependency property in the first place. Just put abool? DialogResult property on your ViewModel and implement INotifyPropertyChanged, and voilà, your ViewModel can close the Window (and set its DialogResult) just by setting a property. MVVM as it should be.

Here's the code for DialogCloser:

using System.Windows; namespace ExCastle.Wpf { public static class DialogCloser { public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged)); private static void DialogResultChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window != null) window.DialogResult = e.NewValue as bool?; } public static void SetDialogResult(Window target, bool? value) { target.SetValue(DialogResultProperty, value); } } }

From: http://blog.excastle.com/2010/07/25/mvvm-and-dialogresult-with-no-code-behind/

Morechanges by me as below:

You can add property DialogResultValue to your ViewModelBase if you have more view model for dialogs. You also can add it directly to your view model not to base.

public abstract class DialogVMBase : VMBase
{
public DialogVMBase()
: base()
{
}

private bool? _dialogResult;
public bool? DialogResultValue
{
get { return _dialogResult; }
set
{
if (_dialogResult != value)
{
_dialogResult = value;
this.RaisePropertyChanged(() => DialogResultValue);
}
}
}
}

Below is example to use it.

In your ViewModel.cs

public class MyViewModel : DialogViewModelBase
{

public RelayCommand OkCommand { get; set; }

public MyViewModel()
: base()
{
OkCommand = new RelayCommand(Ok_Executed);
}

private void Ok_Executed()
{
DialogResultValue = true;
}

}

In your MyWindow.xaml:

<Window ... xmlns:xc="clr-namespace:ExCastle.Wpf"xc:DialogCloser.DialogResult="{Binding DialogResultValue}">

<Button Command="{Binding OkCommand}" Content="OK"/>

In window to use MyWindow:

private void ShowMyWindow_Executed()
{
MyWindow dlg = new MyWindow();

if(dlg.ShowDialog()==true)

{

//When click ok, you can access here.

}

}

Function is successful.

你可能感兴趣的:(dialog)