I show a WPF window using ShowDialog() from the calling window. The window opens and is modal as expected. However, in my OK and Cancel button's click events in the dialog window I set this.DialogResult = true (or false) respectively, and the value does not get set. The window closes as expected, but DialogResult is still null.
Is this a bug in WPF? Or is there a reason the DialogResult property cannot be set yet does not throw an exception? The window is not hosted in a browser.
Code in the calling window:
Window2 win = new Window2();
bool? result = win.ShowDialog();
if (result.HasValue && result.Value) {
//never gets here because result is always null
}
Code in the dialog window:
this.DialogResult = true;
DialogResult
is a nullable bool. However you do not have to cast it to get it's value.
bool? result = myWindow.ShowDialog();
if (result ?? false)
{
// snip
}
The ?? sets the default value to return if the result is null. More information: Using Nullable Types (C# Programming Guide)
As for the original question, the only time I have seen and traced this issue is when the window was being disposed between setting the DialogResult and closing the window. Unfortunately the only advice that I can offer is for you step through your code and check the order of the operations. I believe that I "fixed" it by setting the DialogResult
and then explicitly closing the window.