MessageBox.Show() in WinRT AppsApril 24, 2013
I am currently porting many of my Windows Phone Apps to Windows 8. A huge part of the ViewModel code as well as the XAML code is reusable, which makes porting a smooth and painless operation in general.
One of the first things though that you'll probably notice when you start porting code yourself is the missing MessageBox.Show() SDK function.
The WinRT equivalent is the MessageDialog class which is more versatile but for simple message prompts a call like MessageBox.Show() would still be more useful. That’s why I extended my framework with this replacement class.
2: public enum MessageBoxButton
6: OKCancel = OK | Cancel,
9: public enum MessageBoxResult
15: public static class MessageBox
17: public async static Task<MessageBoxResult> Show(string msg, string title, MessageBoxButton messageBoxButton)
19: var result = MessageBoxResult.Cancel;
20: var md = new MessageDialog(msg, title);
21: if (messageBoxButton.HasFlag(MessageBoxButton.OK))
23: md.Commands.Add(new UICommand("OK", new UICommandInvokedHandler(_ => result = MessageBoxResult.OK)));
25: if (messageBoxButton.HasFlag(MessageBoxButton.Cancel))
27: md.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler(_ => result = MessageBoxResult.Cancel)));
29: await md.ShowAsync();
30: return result;
Now usage of MessageBox.Show() is almost identical to Windows Phone. The only thing to keep in mind though is that due to the built in asynchronous API calls in Windows 8 we have to await calls to our MessageBox class.
1: await MessageBox.Show("Hello WinRT!", "WinRT MessageBox", MessageBoxButton.OK);
This generates following result.