Getting "DialogResult can be set only after Window is created and shown as dialog" when implementing WPF MVVM pattern for form closing
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.
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.