An Alert From the ViewModel

Quite often we want to send an alert from the view model, but you can only do so from the view. We’ve tackled this problem in the past but we think there is room for a simplified and clear step by step explanation.

Begin by creating a new empty Xamarin.Forms application. You’ll need three folders: ViewModel, ServiceInterfaces and Services.

Please note that to complete this program you will need the  Acr.UserDialogs library, which you can download as a NuGet package.

In MainPage.xaml.cs set up the viewmodel to point to MainPageViewModel and set the BindingContext:

protected override void OnAppearing()
{
    base.OnAppearing();

    var vm = new MainPageViewModel();
    BindingContext = vm;
}

It will complain that there is no MainPageViewModel, we’ll create that in a moment, but first let’s create MainPage.xaml:

<StackLayout>
    <Button Text="Send Alert!!" 
            Command="{Binding ShowAlertCommand}" />
</StackLayout>

As you can see, all we have is a button that invokes the ShowAlertCommand bound to our ViewModel. Let’s create the ViewModel which will handle that command

public class MainPageViewModel
{
    public ICommand ShowAlertCommand => 
        new Command(async () => await ShowAlert());

    private async Task ShowAlert()
    {
        var message = "Hello World!";
        var alertService = DependencyService.Resolve<IAlertService>();
        await alertService.ShowMessage("Hello", message);
    }

}

The command invokes ShowAlert (you can name this anything you want) which creates a string message and invokes the alertService by using the DependencyService that you get for free with Xamarin.Forms.

Once we have an interface to the service, we call ShowMessage, passing in a a header string and string to be displayed in the body of the alert box.

If you were using a Dependency Injection Framework such as AutoFac you would have registered the AlertService, as it is, though, we’ll decorate our service with an attribute so that Xamarin.Form’s DependencyService can find it.

First the interface:

public interface IAlertService
{
    Task ShowMessage(string header, string message);
}

And now the implementing class

[assembly: Dependency(typeof(AlertService))]
namespace Alert.Services
{
    public class AlertService : IAlertService
    {
        public async Task ShowMessage(
                  string header, string message)
        {
            var config = new AlertConfig()
            {
                Title   = header,
                Message = message,
                OkText  = "OK",
            };
            await UserDialogs.Instance.AlertAsync(config);
        }
    }
}

Focusing on the first line, we see the attribute that assists the Dependency Service in finding this service.

Implementing the interface we see the ShowMessage method which creates an instance of AlertConfig which contains all the info we need, and then calls AlertAsync through the UserDialogs object passing in the config.

That’s all there is to it. In an upcoming post, we’ll look at using Dependency Injection to make code like this more testable.

Source Code Here.

Jesse Liberty & Rodrigo Juarez

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials and tagged , . Bookmark the permalink.