title: Getting "DialogResult can be set only after Window is created and shown as dialog" when implementing WPF MVVM pattern for form closing
body: <p>I am trying to implement <a href="https://stackoverflow.com/a/3329467/713683">this</a> MVVM pattern for the WPF form closing which is also explained in this <a href="http://blog.excastle.com/2010/07/25/mvvm-and-dialogresult-with-no-code-behind/" rel="noreferrer">blog</a> 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:</p>
  
  <pre><code>DialogResult = true;
  </code></pre>
  
  <p>Here is my ViewModel:</p>
  
  <pre><code>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;
      } 
  </code></pre>
  
  <p>and Here is the XAML View:</p>
  
  <pre><code>&lt;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"&gt;
      &lt;Window.DataContext&gt;
          &lt;local:MainWindowViewModel /&gt;
      &lt;/Window.DataContext&gt;
      &lt;Grid&gt;
          &lt;Grid.RowDefinitions&gt;
              &lt;RowDefinition Height="100"/&gt;
              &lt;RowDefinition Height="40"/&gt;
          &lt;/Grid.RowDefinitions&gt;
          &lt;TextBlock Text="{Binding Text}" Grid.Row="0"/&gt;
          &lt;Button Grid.Row="1" Command="{Binding CloseCommand}"&gt;Close Me&lt;/Button&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>What am I doing wrong here?</p>