-1

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();
}
Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91

2 Answers2

0

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!");
Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
0

I think the recommended way to do this would be to create a client-side dialog or message service that implements an interface:

public interface IDialogService
{
    Task ShowMessageAsync(string message);
}

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

You could then use this service from any class in your app, .e.g.:

IDialogService dialogService = new DialogService();
await dialogService.ShowMessageAsync("message...");

If you adopt the recommended MVVM pattern in your app, you could also inject your view models with the interface:

public ViewModel(IDialogService dialogService)
{
}

...and easily mock out the dialog service in your unit tests, e.g.:

ViewModel vm = new ViewModel(new MockDialogService());

This is not possible if you use a static class or method that you call directly from your view model.

mm8
  • 163,881
  • 10
  • 57
  • 88