hotspring hotspring - 16 days ago 4
C# Question

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

Answer

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.