A frequent scenario in UI applications is gathering information for later use. Dialog windows are a common way to solicit this information. Modal dialogs have an advantage over other types of windows in that the user has to answer your questions before they can continue. This benefit can turn into a curse however if used incorrectly. Anyone who has worked in an application that launches a series of modal dialogs one after another, can attest to the annoyance factor of a poorly written implementation.
WPF doesn't have a separate dialog class. Instead you can treat your window as a normal window or a modal window. Launching a modal dialog is simple in WPF, just call the ShowDialog() method on your window class.
Setting the Dialog result
If you've worked in WinForms prior to moving to WPF you need to learn a few new tricks. That's because the way WPF returns results from a modal dialog is not the same as the Winforms implementation.
Winforms uses the DialogResult enumeration to return the value from a dialog form. Therefore you set the return value to OK, Cancel, Yes, No, Abort, Retry, Ignore or None before returning from the ShowDialog call. In WPF the dialog returns a Nullable
In the following code sample there are two buttons on the dialog. The Yes button has the IsDefault property set to true. IsDefault ties the button to the Enter key, so that pressing the Enter key will fire the Click event. It does not mean that the Yes button will return true for the DialogResult. That is done in the yesButton_Click event procedure.
The No button has the IsCancel property set to true. As a result, pressing the Escape key will close the window. Since the default value for DialogResult is false, that is what is returned when the windows is closed. Another way of saying it; no matter how you close a dialog in WPF it will return false unless you've written code to return true.
Getting the DialogResult
Given what I said in the previous paragraph you might be asking yourself why is the return type of DialogResult typed as Nullable
This was first published in December 2010