How to display alert from ViewModel

  1. Create an interface:
public interface IMessageService
{
    Task ShowAsync(string message);
}
  1. Implement the interface:
public class MessageService : IMessageService
{
    public async Task ShowAsync(string message)
    {
        await App.Current.MainPage.DisplayAlert("YourApp", message, "Ok");
    }
}
  1. Inject the dependency service into App class:
public partial class App : Application
{
    public App()
    {
        //Add the next line
        DependencyService.Register<ViewModels.Services.IMessageService, Views.Services.MessageService>();
        InitializeComponent();
        MainPage = new MainPage();
    }
}
  1. Initialize it in your ViewModel and use:
public class YourViewModel 
{
    private readonly Services.IMessageService _messageService;

    public YourViewModel()
    {
        this._messageService = DependencyService.Get<Services.IMessageService>();

        //Show the dialog with next line
        _messageService.ShowAsync("Hi!!!");
    }
}

You need to pass the Page to the ViewModel

In your view pass the page to the ViewModel with 'this'

public partial class ThePage : ContentPage
{

    ViewModel viewModel;

    public ThePage()
    {
        InitializeComponent();

        viewModel = new ViewModel(this);
}

and then in your view model

public class ViewModel
{

    Page page;
    public ViewModel(Page page)
   {
     this.page = page;

     //SOME CODE 
    }

   async void ValidateUser()
    {
        await page.DisplayAlert("Alert from View Model", "", "Ok");
    }
 }

If you want to keep it pure, you should probably refrain from using alerts in the traditional way and find some way to collect input that you can trigger from toggling a property.

However, there is another, simpler way. You could use ACR.UserDialogs. If you're not using .NET Standard yet you will need to install an older version of the NuGet package. Remember to install it in both your shared project as well as the platform projects. It might also need some initialization code depending on the platform, make sure to check the readme.

You can now either call the instance directly with: UserDialogs.Instance and then a method to show an alert or whatever you need. To keep it a bit more MVVM like you could also register this instance with it's interface counterpart and have it injected into your view models.