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?
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With