Tuesday, May 18, 2010

Closing Modal Dialog Window in WPF

If it is a modal dialog box, then it most probably has OK, Cancel buttons. If it has OK, Cancel buttons, them most probably the “client initiator” wants to know if Ok was pressed or not.

image

Remember WinForms had DialogResult enumeration? It is a bit different with WPF, ShowDialog() returns bool?.

bool? result = form.ShowDialog();if (result.HasValue && result.Value){ DoMyThing();}

When will result.Value be false?  Make sure that you do this only for True/Ok case, the default is false:

private void Ok_Click(..){ this.Close(); this.DialogResult = true;}

and one more thing. To close dialog on Esc, you want this:

image

For OK button you want this:

image

This way, when user presses Enter, OK button is pressed.

 

Warning about IsCancel and Cancel button. There seems no way to Cancel the “Cancel event”. So if user clicks Cancel, windows is going to be closed. If you know a way for canceling the closure, please post.

1 comments:

Alexander Uvarov said...

Looks like this.DialogResult = true; must be before this.Close();

Post a Comment