Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display alert box with Xamarin.Forms for validation?

How to display alert box with Xamarin.Forms for validation?

I know that we can display alert using below code from ContentView code behind but I want to display alertbox from my ViewModel.

DisplayAlert ("Alert", "You have been alerted", "OK");

I've registered my ViewModel against View with below code.

ViewFactory.Register<[ContentPage], [ContentPageViewModel]> (); 
like image 661
Nirav Mehta Avatar asked Dec 17 '14 06:12

Nirav Mehta


2 Answers

You can display an alert from anywhere in the Xamarin.Forms project via the MainPage property of the static App.Current e.g.

await App.Current.MainPage.DisplayAlert("Test Title", "Test", "OK");
like image 63
Martin Rhodes Avatar answered Oct 19 '22 12:10

Martin Rhodes


You can use:

Application.Current.MainPage.DisplayAlert(title, message, buttonText)

But, this is a bad practice to use it inside the view model.

Instead, the best practice, in my opinion, would be decoupling this from the view models and pages. The solution is to create a service responsible for displaying the alerts in your application. Below you can find the simple answer to your problem. However, DisplayAlert method has many overloads, and you can add new methods to your service that will use the overloads.

Two Simple examples in one code:

First implement interface for your service:

public interface IDialogService
{
    public Task ShowErrorAsync(string message, string title, string buttonText);
    public Task ShowErrorAsync(string message, string title, string buttonText, Action CallBackAferHide);
}

Then, implement the interface in the concrete implementation:

public class DialogService : IDialogService
{
    public async Task ShowErrorAsync(string message, string title, string buttonText)
    {
        await Application.Current.MainPage.DisplayAlert(title, message, buttonText);
    }

    public async Task ShowErrorAsync(string message, string title, string buttonText, Action CallBackAferHide)
    {
        await Application.Current.MainPage.DisplayAlert(title, message, buttonText);
        CallBackAferHide?.Invoke();
    }
}

The first method allows you to display alert and the second allows you to provide a call back method that will be called after user dismiss the alert box - for example navigates back to the previous page.

The second method can be used in both cases, just call:

await ShowErrorAsync("message", "title", "OK", null);

The CallBackAferHide?.Invoke(); first checks if Action was provided, then invokes if it is not null.

In your view model, inject the service and just call its method providing parameters.

I hope that will help :). All the best!

like image 26
R. Fajkowski Avatar answered Oct 19 '22 12:10

R. Fajkowski