Home > C#, MVVM, Windows Phone, WinRT > DialogService in MVVM Light V5

DialogService in MVVM Light V5

14/10/2014

Some days ago we talked about the new release of MVVM Light Toolkit and, in particular, we presented the new NavigationService.

The other service that is shipped with MVVM Light V5 is DialogService, that is able to show message dialogs in our apps. To use it, we simply need to register this type in the ViewModelLocator class:

public ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<IDialogService, DialogService>();
    // Other registrations...

    SimpleIoc.Default.Register<MainViewModel>();
}

Basically, the IDialogService interface contains the ShowMessage method, with some overloads. For example:

public class MainViewModel : ViewModelBase
{
    private IDialogService dialogService;

    public RelayCommand TestDialogServiceCommand { get; set; }

    public MainViewModel(IDialogService dialogService)
    {
        this.dialogService = dialogService;

        TestDialogServiceCommand = new RelayCommand(async () =>
        {
            // Simple message without callback.
            await dialogService.ShowMessage("Simple message text", "Title");

            // Message with custom buttons and callback action.
            await dialogService.ShowMessage("Are you sure you want to continue?", 
                "Confirmation",
                buttonConfirmText: "Continue", buttonCancelText: "Discard", 
                afterHideCallback: (confirmed) =>
                {
                    if (confirmed)
                    {
                        // User has pressed the "confirm" button.
                        // ...
                    }
                    else
                    {
                        // User has pressed the "cancel" button
                        // (or has discared the dialog box).
                        // ...
                    }
                });
        });
    }
}

At line 15, we use the simplest version of ShowMessage: we just show a dialog box with a message and a title. Instead, the second example (lines 18-25) shows a message box with two buttons, Continue and Cancel; when the user taps one of them (or discard the question), the afterHideCallback action will be invoked. It will get a boolean parameter indicating if the “confirm” button (true) or the “cancel” button (false) was pressed (or if the dialog was discarded).

The IDialogService interface exposes also the ShowError method, that can be used to display information about an error (it accepts an Exception as first argument). However, we must notice that on some platforms, like Windows Store and Windows Phone, ShowError has the same output of ShowMessage (because these platforms don’t have the concept of error message box).

Categories: C#, MVVM, Windows Phone, WinRT
%d bloggers like this: