如何链接单击我的视图模型的按钮?

时间:2017-09-08 12:05:46

标签: xamarin xamarin.forms

我有这段代码:

<Button x:Name="resetButton" Text="Reset All Points to Zero" Command="{Binding ResetButtonClickedCommand}">
</Button>

和背后的视图模型:

    private ICommand resetButtonClickedCommand;

    public ICommand ResetButtonClickedCommand
    {
        get
        {
            return resetButtonClickedCommand ??
            (resetButtonClickedCommand = new Command(async () => await resetButtonClicked()));
        }
    }

    async Task resetButtonClicked()
    {
        if (App.totalPhrasePoints < 100 || await App.phrasesPage.DisplayAlert(
            "Reset score",
            "You have " + App.totalPhrasePoints.ToString() + " points. Reset to 0 ? ", "Yes", "No"))
            App.DB.ResetPointsForSelectedPhrase(App.cfs);
    }

我已完成绑定,因为它与XAML中许多其他内容使用的绑定相同

然而,当我单击按钮时没有任何反应,并且未达到get和方法中的断点。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

首先确保您的绑定上下文设置为此页面和视图模型。

然后,我建议对你的方法采用不同的方法:

public YourViewModel()
{
    ...

    ResetButtonClickedCommand = new Command(ExecuteReset);

    ...
}

private async void ExecuteReset()
{
    if (App.totalPhrasePoints < 100 || await App.phrasesPage.DisplayAlert(
        "Reset score",
        "You have " + App.totalPhrasePoints.ToString() + " points. Reset to 0 ? ", "Yes", "No"))
        App.DB.ResetPointsForSelectedPhrase(App.cfs);
}