简体   繁体   中英

Xamarin.Forms MVVM getting responce from DIsplayAlert

How to work with DisplayAlert() correctly from MVVM view?

I have some screen and ViewModel for it. Inside the ViewModel I defined some Actions :

class PageViewModel : INotifyPropertyChanged
{
    public Action DisplayDataSavedPromt;
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public ICommand SaveCommand { protected set; get; }

    public PageViewModel()
    {
        SaveCommand = new Command(OnSubmit);
    }

    public void OnSubmit()
    {           
        DisplayDataSavedPromt();
    }

}

And then I'm calling it from View Page.cs :

public Page ()
{
    var vm = new PageViewModel();
    this.BindingContext = vm;
    vm.DisplayDataSavedPromt += () => DisplayAlert("Success", "Your data are saved", "OK");
    InitializeComponent ();
}

And it's working fine, but I can't understand how can I bind some actions to this Alert's buttons? Eg when user clicks OK inside Alert, open new page.

Should I do it inside ViewModel somehow or inside View?

You can try this in your view model

var res = await App.Current.MainPage.DisplayAlert("Success", "Your data are saved", "Ok", "Cancel");

if(res){//logic} else {//logic}

You need to await the user action, and then parse the result, like this:

var result = await DisplayAlert("Success", "Your data are saved", "Ok", "Cancel"); 

//User pressed OK
if(result == true) 
{
    // do your logic
}
else // User pressed Cancel
{ 
    // do your logic
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM