Getting "DialogResult can be set only after Window is created and shown as dialog" when implementing WPF MVVM pattern for form closing

I am trying to implement this MVVM pattern for the WPF form closing which is also explained in this blog and I am getting System.InvalidOperationException with error message "DialogResult can be set only after Window is created and shown as dialog." when I am trying to set the Dialog Result on Close button command:

DialogResult = true;

Here is my ViewModel:

class MainWindowViewModel:INotifyPropertyChanged
{
    private bool? dialogResult;
    public bool? DialogResult
    {
        get { return dialogResult; }
        set
        {
            if (value != this.dialogResult)
            {
                this.dialogResult = value;
                OnPropertyChanged("DialogResult");
            }
        }
    }

    public string Text
    {
        get { return "Hello!"; }
    }

    void CloseCommandExecute()
    {
        this.DialogResult = true;
    } 

and Here is the XAML View:

<Window x:Class="WpfApplication.Mvvm.Windowclosing.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication.Mvvm.Windowclosing"
        local:DialogCloser.DialogResult="{Binding DialogResult}"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
        <TextBlock Text="{Binding Text}" Grid.Row="0"/>
        <Button Grid.Row="1" Command="{Binding CloseCommand}">Close Me</Button>
    </Grid>
</Window>

What am I doing wrong here?


Solution 1:

Setting a dialog result only works when you open your form with ShowDialog(). You get this error when you try to set the dialog result on a form opened with Show().

Solution 2:

I came across this problem when I created a window, which was called through ShowDialog(). In the window, I had an Ok_Clicked which included a bunch of statements. In order to 'guarantee' the dialog returned false if there was anything wrong I first initialized the DialogResult to false. If everything was right, I then set DialogResult to true and closed the window. I kept getting the same exception.

I learned that if the DialogResult was not set to true, ShowDialog would always return false. When I removed DialogResult = false in the beginning of the Ok_Clicked, I no longer got the exception.

Solution 3:

I came across an alternate answer that may help others. I ended up calling Close() on the window before setting the DialogResult. Make sure you don't do that--it will cause this error.