Message Dialog in Windows Store App

After the release of Windows 8 i.e. 26th October developers have gone crazy about developing Metro style applications. I have been developing for Windows previously also and MessageBox was the most used control, but in Metro style apps I didn't find it, so this is simply an article to guide you through the use of message boxes in Metro style apps which are called Popups here. The message box here is fully user-defined, we can add the commands to the message box and also add an action with it. Here is a walkthrough of doing that.

The first step is to create a new Metro Style Blank App Project.

MsgBxMtr1.jpg

A blank project will open in front of you. We will add our code into "MainPage.xaml.cs". In the following project I will add the message box under the "OnNavigatedTo" event so that as soon as the Application is opened the message box will appear.

Now we will add a namespace for the message box in Metro style apps:

using Windows.UI.Popups;

Now its time to enter our actual code. Here is a code snippet:

MsgBxMtr2.jpg

In the first line a new object for the MessageDialog is created which is saved in a "var md". MessageDialog has an argument which is the message box text which is displayed when the message box appears:

var md = new MessageDialog("Are you sure you want to exit");

The second line adds a new command to the message box i.e. "Yes"; the new UICommand creates an object for a new command and the new UICommandInvokedHandler adds the action to the corresponding command; here the action we have added is: Application.Current.Exit(); this closes the application.

md.Commands.Add(new UICommand("Yes", (UICommandInvokedHandler) =>
{
Application.Current.Exit();
}));

The third line adds another command i.e. "No". This will cause nothing to the application and the application will continue.

md.Commands.Add(new UICommand("No"));

Debug the app to see the result:

MsgBxMtr3.jpg

Next Recommended Readings