Spyros Savvides Spyros Savvides - 2 months ago 13
C# Question

How to integrate an AlertDialog with mvvmcross

I'am trying to show notification(messages) to the user using an android alertdialog.The pattern I use for my project is MVVM(MVVMCross).

I'am passing my messages to viewmodel properties eg:

private string _messageHeader;

public string MessageHeader
{
set { _messageHeader = value; }

get { return _messageHeader = "A test messageaHeader"; }
}

private string _message;

public string Message
{
set { _message = value; }

get { return _message = "A test message"; }
}


and then I call my properties from the view and pass then pass them to the alertdialog.

public StockSearchMasterViewModel StockSearchMasterViewModel
{
get { return (StockSearchMasterViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}



AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog alertDialog = builder.Create();

alertDialog.SetTitle(StockSearchMasterViewModel.MessageHeader);
alertDialog.SetMessage(StockSearchMasterViewModel.Message);
alertDialog.SetButton("OK", (s, ev) => Command.Execute(null));
alertDialog.SetButton2("Cancel", (s, ev) => alertDialog.Hide());
alertDialog.Show();
.
.
.


A new message from viewmodel, a new alertdialogpopup

alertDialog.SetTitle(StockSearchMasterViewModel.MessageHeader2);
alertDialog.SetMessage(StockSearchMasterViewModel.Message2);
alertDialog.SetButton2("OK", (s, ev) => alertDialog.Hide());
alertDialog.Show();


What I'am trying to achieve here is when the user presses OK in the dialog an ICommand will execute a method in the viewmodel where there will be a second message if some condition is valid or invalid. My problem is the second message. I do not know how to pass it again to the alert dialog since the alert dialog will not stop the main thread to the .Show() (assuming that because is an asynchronous operation) and will curry on until the function has completed its cycle.

Answer

The most complete way I've found to do this is using the interaction request pattern - see: MvvmCross Dialog

However, other ways are available - and are easier to follow - especially using the messenger or injecting a custom IDialogService interface. For more on these, see Display Error or Information from ViewModel to View

Comments