Search code examples
c#uwpmessagedialog

Recommend way to call UWP MessageDialog in App.xaml.cs


I have a MessageDialog with just a single button in my App.xaml.cs I wish to use it from other pages. Several approaches seem to work but as there are subtleties with async and Tasks is a particular one correct?

The following is called with await App.mymessagebox("A message"):

public static Task async mymessagebox(string the_message)
{
   MessageDialog messagedialog=new MessageDialog(the_message);
   await messagedialog.ShowAsync();
}

The following is called with App the_app=(App)Application.current; await the_app.mymessagebox("A message");:

public async Task mymessagebox(string the_message)
{
   MessageDialog messagedialog=new MessageDialog(the_message);
   await messagedialog.ShowAsync();
}

Solution

  • Both of these approaches are functionally equivalent, but the preferred solution would be not to put the methods in the App class. Instead, you should create a separate class, which could be even static, that you would use to access these reusable message dialogs. The reason for this is that is separation of concerns. App class should only contain code related to the overall app initialization and lifecycle. This is a helper method simplifying the display of dialogs, so it should reside elsewhere:

    public static DialogHelpers
    {
        public static async Task ShowMessageAsync(string message)
        {
           MessageDialog messageDialog = new MessageDialog(message);
           await messageDialog.ShowAsync();
        }
    }
    

    To adhere to the convention, you should add the Async suffix to the name of the method to make it clear the method is async and should be awaited.

    Calling this helper method will now look like this:

    await DialogHelpers.ShowMessageAsync("Hello, world!");