views:

654

answers:

2

WPF's Window.ShowDialog method returns a nullable boolean. So does CommonDialog.ShowDialog.

Now, I understand cases where these would return false (user clicked Cancel or pressed Esc), and when they would return true (code sets Window.DialogResult to true, probably in response to OK being clicked). But null?

My first thought is that clicking the title bar's Close button might return null. But the docs state (and I confirmed by testing) that the title-bar Close button is treated as a Cancel.

So when would Window.ShowDialog or CommonDialog.ShowDialog ever return null?

+4  A: 

The method always returns true or false, and this is always equal to the DialogResult property of the window at the time it closes.

But the DialogResult property is null before the window is closed, and another thread could check the property. So it kind of makes sense that the return value is a nullable boolean to match the property, even though it is never actually null.

UncleO
Not sure where you get the idea that another thread could check DialogResult. If you try, you get an InvalidOperationException ("The calling thread cannot access this object because a different thread owns it.")
Joe White
Not another thread, but any code running (say) on an event handler on the dialog could retrieve the value of DialogResult before it completes. Personally I think it's a poor design choice. It should have been non-nullable, the getter throwing an exception if accessed before the dialog quits.
Daniel Earwicker
+1  A: 

If I return DialogResult = null in the Click event for a button, the window remains open.

private void OkButton_Click(object sender, RoutedEventArgs e)
{
   Button btn = sender as Button;
   if ( btn != null )
   {
       // forces all control to update...
       btn.Focus();
   }

   // TEST IF OK TO CLOSE
   bool rc = _vm.ProcessOkCommand();
   if (rc)
   {
      DialogResult = true;
   }
   else
   {
      DialogResult = null;
   }
}


<Button Content="OK" Name ="cmdOK" IsDefault="True" Click="OkButton_Click"/>
Zamboni
Right, that's my point -- it looks like ShowDialog won't ever return null.
Joe White