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?