In recent articles in the WPF tutorial we have looked at the Window control and how it can be used to create custom dialog boxes. In some cases, you might wish to show a dialog box only to display a message or to ask the user a simple yes/no question. Creating a custom dialog box for this would be time-consuming, so Microsoft has included a basic message box within the .NET framework.
The MessageBox class allows you to display a modal dialog box with various elements. All message boxes include a string for the message itself. You can also add a caption, for the pop-up window's title bar, and an image to differentiate between questions, informational messages, warnings, errors and other items. Lastly, you can decide upon the buttons to display. When the user clicks a button to close the dialog box, you can determine which one was used.
Displaying a Simple Message
The most basic message boxes include a single piece of text and an "OK" button, which closes the dialog box and returns control to the calling window. We'll start with an example of such a message box and then expand upon it to show the other features. Start by creating a new WPF application in Visual Studio named, "MessageBoxDemo". Once the new solution is ready, replace the XAML in its main window with the following code:
Title="Message Box Demo" Height="100" Width="200"
<TextBlock Name="ButtonLabel" HorizontalAlignment="Center"
Margin="7">No button pressed</TextBlock>
<Button Grid.Row="1" Click="Show_Click" Margin="3">Show Message Box</Button>
We will use the window that the above code creates to launch message boxes when the button is clicked. The TextBlock will show the name of the button that the user clicked to close the message box window.
To display a message box, you call the Show method of the MessageBox class. This static method has many overloaded versions. We won't look at every variation in this article but will see most of the options that you can use. The most basic overload requires a single string argument, which contains the message to display.
Switch to the code behind the window and add the following method. This will show a message box when the button is clicked.
private void Show_Click(object sender, RoutedEventArgs e)
Run the program and click the button to see the results. Note that the message box is modal, preventing you from switching back to the main window until you click the OK button.
Adding a Caption
The basic style of message box does not include a caption in the title bar. However, you can easily add one by using a second string parameter. Updating the line of code that displays the message box, as follows:
MessageBox.Show("Hello, world!", "Welcome");
Run the program and click the button again. The message box now includes the extra argument's text in its title bar.
12 July 2015