【问题标题】:How can I link a button clicked to my View Model?如何将单击的按钮链接到我的视图模型?
【发布时间】:2018-02-17 08:40:49
【问题描述】:

我有这个代码:

<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 和方法中的断点没有到达。

是不是我做错了什么?

【问题讨论】:

  • 为什么要检查 Null 任务的返回?它不返回任何内容,因此它不能为空。此外,您不需要使用 Button 的 command 属性,我很确定您可以使用 OnClicked 属性并将其分配给您的视图模型?

标签: xamarin xamarin.forms


【解决方案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);
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多