xamarinxamarin.formsalert

How do I create an alert popup from my ViewModel in Xamarin?


I'm developing my Xamarin app with the MVVM pattern. I want to display an alert to the user when the user presses a button.

I declare my ViewModel with

class MainPageViewModel : BindableBase   {

Unfortunately, I'm not able to access a Page object from within the ViewModel directly. How do I best go about displaying my alert?


Solution

  • To display Alert write below code in your ViewModel class

    public class MainViewModel
    {
        public ICommand ShowAlertCommand { get; set; }
        public MainViewModel()
        {
            ShowAlertCommand = new Command(get => MakeAlter());
        }
        void MakeAlter()
        {
            Application.Current.MainPage.DisplayAlert("Alert", "Hello", "Cancel", "ok");
        }
    }
    

    Set your Command to Button in xaml

    <StackLayout>
    <Button Text="Click for alert" Command="{Binding ShowAlertCommand}"
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />
    </StackLayout>
    

    Set BindingContext in code behind of your xaml file. If you xaml file MainPage.xaml

    public MainPage()
    {
        InitializeComponent();
        BindingContext = new MainViewModel();
    
    }