Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert Dialog in ViewModel - MVVMCross

In the ViewModel, I have Save method where I check isValid property.

If isValid is false, then I want to display an error message.

Since AlertDialog is platform specific, I wonder how do you handle that situation in the ViewModel?

public void Save()
{
  if (isValid)
  {
      OnExit(this, null);
   }
   else
   {
      //issue an alert dialog here
   }
}

Update

I have used the following plugin and added the following line of code as follows, but it throws an error.

else
{
    Mvx.Resolve<IUserInteraction>().Alert("it is not valid");
}

enter image description here

Update 2

Chance.MvvmCross.Plugins.UserInteraction is a namespace but it is used as a type error.

enter image description here

Update 3

I have added Acr.UserDialogs plugin and called as follows, but I have got the same error.

Mvx.Resolve<IUserDialogs>().Alert("it is not valid");

enter image description here

like image 516
casillas Avatar asked May 11 '16 16:05

casillas


2 Answers

Using ACR User Dialogs is the simplest approach.

In your App.cs (Core/PCL) you will need to register the interface:

public class App : MvxApplication
{
    public override void Initialize()
    {
       // Example Other registrations
        CreatableTypes()
            .EndingWith("Service")
            .AsInterfaces()
            .RegisterAsLazySingleton();

        Mvx.RegisterSingleton<IUserDialogs>(() => UserDialogs.Instance);
    }
}

Then you can call your alert form your ViewModel.

Mvx.Resolve<IUserDialogs>().Alert("it is not valid");

Note for Android Platform support

Then if you are supporting Android you will need to initialize UserDialog with an instance of the activity context. This will have to be done in each activity that you will be making use of UserDialogs or if you have a shared base activity you can do it there.

[Activity]
public class MainActivity : MvxActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.activity_main);

        // Initialize Acr UserDialogs
        UserDialogs.Init(this);
    }
}

Alternatively

You can follow the Mvvmcross document on using platform specific implementations of an interface if you need a more custom modal implementation.

like image 200
Plac3Hold3r Avatar answered Nov 20 '22 23:11

Plac3Hold3r


This is how I handle the Alert messages in the viewmodel. Try this.

await App.Current.MainPage.DisplayAlert("Active subscription required", "You do not have an active subscription for Part 2 exams", "OK");
like image 4
Nurhak Kaya Avatar answered Nov 21 '22 00:11

Nurhak Kaya