A common user interaction is the humble MessageBox. Doing a quick web search of “silverlight messagebox” tends to produce a number of results lamenting how MessageBox is not available in Silverlight, and discussing various techniques to simulate a MessageBox.
While it’s true that there wasn’t a MessageBox until the Release Candidate, there IS a MessageBox class in the final (RTW, Release To Web) version of Silverlight 2.0!
It’s System.Windows.MessageBox. It’s a bit limited:
- It doesn’t display an icon on Windows (although according to the docs, the Macintosh version does display an icon!)
- It offers a choice of a single button called OK or two buttons: OK and Cancel.
One nice part of the MessageBox is that it allows customization of the title bar text (unlike the Javascript alert() and confirm() dialogs). And it’s a bit less code than other alternatives, and it’s more visually consistent across various browsers than the Javascript alternatives. Here’s the code to generate a MessageBox with all the options:
MessageBox.Show("This is the messageBoxText",
"This is the caption",
MessageBoxButton.OKCancel);
This renders like this on Windows Vista:
If you only want the OK button, just pass MessageBoxButton.OK as the last parameter:
Finally, there’s a simpler overload that only takes the messageBoxText:
MessageBox.Show("This is the messageBoxText");
This generates a MessageBox with only the OK button and no text in the title bar:
In addition, the Show method returns a MessageBoxResult, which has the following values: OK, Yes, No, Cancel, None. According to the docs, the Yes, No, and None values are currently unused. (This makes sense, as there are only OK and Cancel buttons.)
Here’s a link to the documentation: http://msdn.microsoft.com/en-us/library/system.windows.messagebox(VS.95).aspx