tags:

views:

2160

answers:

4

How do I get System.Windows.ShowDialog() to return 'true'?

I am a little new to this. System.Windows.ShowDialog's return type is bool? It is supposed to return true when you hit Submit, and false when you hit Cancel. But I am not sure how to designate which button is the official submit button.

EDIT: On a related note, I am curious as to how it can return null.

A: 

ShowDialog returns a DialogResult, not a boolean.

ctacke
The first Google hit for his (mistyped) class name shows an MSDN article for the API returning a bool. He tagged his question with "wpf" and ".net". The WPF call returns bool.
JMD
Really? I just googled "showdialog method" to verify that and the first 2 results sure look like it returns a DialogResult to me.
ctacke
Ahhhh! If I look at the tag I see "WPF". How sneaky. Under Windows.Forms it's a DIalogResult, and that's what I just assumed. SHould probably have made that more clear in the question (or I should read more carefully).
ctacke
Yes, (*shakes fist in the direction of Redmond*) it is frustrating that they change result types for identically named methods.
JMD
Yeah, I'd have to vote that the people who named it should be slapped. And hard.
ctacke
+6  A: 

http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog.aspx

ShowDialog returns a Nullable<(Of <(T>)>) Boolean value that specifies whether the activity was accepted or canceled. The return value is the value of the DialogResult property before a window closes (see DialogResult).

Basically, you decide by setting the value of the DialogResult, not by hitting a particular button -- you decide what the button does.

JMD
+3  A: 

In WPF, set the Button.IsDefault property to true to specify that a button is the "submit" button for a window. I'm not 100% sure that this will make the window close with a DialogResult of true. If it doesn't, you just need to handle its Click event thusly:

this.DialogResult = true;

Edit

Likewise, you can use the Button.IsCancel property to have a button be the "cancel" button for a form.

Edit 2

I believe the reason ShowDialog is nullable is that since it's null up until the form is submitted or canceled, you could test for that if you were watching the dialog in a background thread. I haven't tried that, but it seems like a logical reason why they'd introduce a third "unknown" (null) state to the property.

Matt Hamilton
A: 

if you set DialogResult to true ShowDialog returns true, if you set DialogResult to false ShowDialog returns false if the dialog is closed without setting DialogResult (the user clicks on the red X in the top right corner) ShowDialog will return null.

Setting IsDefault to true will cause the button to look a little different and pressing enter will "click" this button.

If you set IsCancel to true the pressing esc will "click" this button.

Nir