Xamarin.Forms MVVM得到DIsplayAlert

时间:2018-09-26 12:00:56

标签: c# xamarin mvvm xamarin.forms

如何从MVVM视图正确使用DisplayAlert()

我有一些屏幕和ViewModel。 在ViewModel内部,我定义了一些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();
    }

}

然后我从View Page.cs调用它:

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

它工作正常,但是我不明白如何将某些操作绑定到此警报的按钮? 例如。当用户在“警报”中单击“确定”时,打开新页面。

我应该在ViewModel内部还是在View内部进行操作?

2 个答案:

答案 0 :(得分:2)

您可以在视图模型中尝试

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

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

答案 1 :(得分:1)

您需要等待用户操作,然后解析结果,如下所示:

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
}