MessageBox.Show() in WinRT Apps
April 24, 2013I 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.
1: [Flags]
2: public enum MessageBoxButton
3: {
4: OK,
5: Cancel,
6: OKCancel = OK | Cancel,
7: }
8:
9: public enum MessageBoxResult
10: {
11: OK,
12: Cancel,
13: }
14:
15: public static class MessageBox
16: {
17: public async static Task<MessageBoxResult> Show(string msg, string title, MessageBoxButton messageBoxButton)
18: {
19: var result = MessageBoxResult.Cancel;
20: var md = new MessageDialog(msg, title);
21: if (messageBoxButton.HasFlag(MessageBoxButton.OK))
22: {
23: md.Commands.Add(new UICommand("OK", new UICommandInvokedHandler(_ => result = MessageBoxResult.OK)));
24: }
25: if (messageBoxButton.HasFlag(MessageBoxButton.Cancel))
26: {
27: md.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler(_ => result = MessageBoxResult.Cancel)));
28: }
29: await md.ShowAsync();
30: return result;
31: }
32: }
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.