Prasanth
Prasanth

Reputation: 329

How can I display an Alert view from view model in Xamarin.forms

I working on Xamarin hybrid application, right now I am using MVVM architecture. My view model is 'INotifyPropertyChanged' interface class. I parse json data on this viewmodel class. Now I want to display alert if failed to read json data from server or need to show error message to user on Alert. But it not working. I know 'DisplayAlert()' will work only on Page Classes. So how can I show the alert from ViewModel Page. I tried this also, but not working;

await App.Current.MainPage.DisplayAlert(Constant.KSorry, Constant.KNoDataAvailable, Constant.KOK);

Upvotes: 1

Views: 1780

Answers (3)

joyshinde
joyshinde

Reputation: 23

On MVVM we can try the following

  1. When you have just one button on the alert

DeviceDevice.BeginInvokeOnMainThread(() => { await App.Current.MainPage.DisplayAlert("Hello", "message", "OK"); });

  1. When you have more than one button on the alert dialog

var response = await App.Current.MainPage.DisplayAlert("Hello", "message", "OK", Cancel");

No need for Device.BeginInvokeOnMainThread in this case

Upvotes: 0

hashimks
hashimks

Reputation: 1225

You can try putting the code inside Device.BeginInvokeOnMainThread

like,

Device.BeginInvokeOnMainThread(() =>
{
   await App.Current.MainPage.DisplayAlert("Hello", "message", "OK");
});

Upvotes: 2

Prasanth
Prasanth

Reputation: 329

Displaying an alert from main thread should work from ViewModel 'INotifyPropertyChanged' Interface class. Check the code

if (arrayAlbumList == null) {
   Device.BeginInvokeOnMainThread(() => {
                App.Current.MainPage.DisplayAlert(Constant.KSorry, 
                Constant.KNoDataAvailable, Constant.KOK);
   });
}
else {
  // binding the object here using array
}

Upvotes: 1

Related Questions