如何在Xamarin中进行displayalert验证后运行ViewModel命令

时间:2016-09-10 15:44:37

标签: xaml mvvm xamarin

我的ViewModel中有一个删除对象命令。该命令绑定到该按钮。到现在为止还挺好。当我单击该按钮时,该对象将从db中删除。现在,显然,这需要进行验证,因此我使用DisplayAlert显示“您确定要删除吗?”给用户。这会显示,但该项目仍会在按钮单击时删除,这是有意义的。我很难理解如果用户选择“是”,如何只在ViewModel中运行我的命令。

XAML按钮:

 <Button Text="Delete player" Command="{Binding DeleteCommand}" Clicked="DeletePlayerEvent"></Button>

点击活动:

 private async void DeletePlayerEvent(object sender, EventArgs e)
    {
        bool answer = await DisplayAlert("Notification", "Are you sure you want to delete this player?", "Yes", "No");
        //if (answer == true)??????
       // {
            //Can I run the command from here?
        //}
    }

ViewModel命令

 public Command DeleteCommand
    {
        get
        {
            return new Command(async () =>
            {
                var playerServices = new PlayerServices();
                await playerServices.DeletePlayerAsync(_Player.Id);
            });
        }
    }

1 个答案:

答案 0 :(得分:1)

这里的问题是你正在一起进行Command绑定和事件订阅。

这两者都是单独解雇而不是彼此依赖。

您可以将它们连接在一起的一种方法是在用户选择&#34;是&#34;

时,从您的按钮点击事件调用ViewModel的DeleteCommand

要抓住点击事件中的DeleteCommand属性(假设它写在您的代码隐藏文件中):

var viewModel = this.BindingContext as YouViewModel
viewModel.DeleteCommand.Execute();

希望有所帮助!