A simple popup message with Windows Runtime ("Modern UI")

Posted: (EET/GMT+2)

 

If you have been doing .NET development especially with graphical desktop applications, you've without doubt used the MessageBox class and its Show method to display simple messages on the screen. I've used this class countless times, and among else, it's great for demos, simple testing, debugging, or just for fun.

Today, we're posed to get our .NET applications on top of Windows Runtime (WinRT) or "Modern UI", which in turn means many changes to the way we build our applications, especially in the UI front. While doing so, it's often useful to be able to display quick status messages. In the Windows Runtime world, there's a class called MessageDialog, which lives in the Windows.UI.Popups namespace. Now, this class allows you to show a message "box" similar to the way it works on the desktop side, but then again, using this class isn't as straightforward as the original.

To help you using the good ol' MessageBox feature again, I've written myself a simple helper routine, which goes like this:

using Windows.UI.Popups;
...
namespace MyTools
{
    internal enum MessageBoxButtons
    {
        OK,
        Cancel,
        OKCancel,
        Unknown
    }

    internal static class MessageBox
    {
        internal static async Task Show(
            string content, string title = "", MessageBoxButtons buttons = MessageBoxButtons.OK)
        {
            MessageDialog dialog = null;
            if (string.IsNullOrEmpty(title))
            {
                dialog = new MessageDialog(content);
            }
            else
            {
                dialog = new MessageDialog(content, title);
            }

            // add the buttons
            bool addOK = ((buttons == MessageBoxButtons.OK) ||
                          (buttons == MessageBoxButtons.OKCancel));
            bool addCancel = ((buttons == MessageBoxButtons.Cancel) ||
                          (buttons == MessageBoxButtons.OKCancel));
            MessageBoxButtons clickedButton = MessageBoxButtons.Unknown;
            if (addOK)
            {
                dialog.Commands.Add(new UICommand("OK",
                    (command) => clickedButton = MessageBoxButtons.OK));
            }
            if (addCancel)
            {
                dialog.Commands.Add(new UICommand("Cancel",
                    (command) => clickedButton = MessageBoxButtons.Cancel));
            }

            // show the dialog and wait for the user's choice
            var result = await dialog.ShowAsync();

            // return the button that the user clicked
            return clickedButton;
        }
    }
}

Using this class is simple: create a method with the async modifier, and then summon the message to the screen by saying:

await MessageBox.Show("Hello, World!");

Simple enough. Hope this helps!

Keywords: WinRT, Metro, C#, MessageBox.Show equivalent in Windows 8 store apps