可以在 MvvmCross 中执行

CanExecute in MvvmCross

我正在开发一个 Xamarin.Android 应用程序,我正在使用 MvvmCross。在我的代码中 DecreaseCommand 不起作用:

public class CartItemViewModel : MvxNotifyPropertyChanged
{      
    private int quantity = 0;      

    public CartItemViewModel()
    {
        IncreaseCommand = new MvxCommand(ExecuteIncreaseCommand, CanExecuteIncreaseCommand);
        DecreaseCommand = new MvxCommand(ExecuteDecreaseCommand, CanExecuteDecreaseCommand);
        Delete = new MvxCommand (() => {Quantity++;});
    }        

    public int Quantity
    {
        get { return quantity; }
        set
        {
            quantity = value;
            RaisePropertyChanged("Quantity");
            RaisePropertyChanged("SubTotal");
        }
    }

    public ICommand IncreaseCommand { get; set; }
    public ICommand DecreaseCommand { get; set; }
    public ICommand Delete { get; set; }


    private void ExecuteIncreaseCommand()
    {
         Quantity++;
    }

    private bool CanExecuteIncreaseCommand()
    {
        return true;
    }

    private void ExecuteDecreaseCommand()
    {
        Quantity--;
    }

    private bool CanExecuteDecreaseCommand()
    {
        return Quantity > 0;
    }


}

我怀疑 CanExecuteDecreaseCommand 没有触发,这段代码有什么问题吗?

您在更新 Quantity 属性 时忘记调用 RaiseCanExecuteChanged

此外,您无需设置始终 returns 为真的 CanExecute

public class CartItemViewModel : MvxNotifyPropertyChanged
{      
    private int quantity = 0;      

    public CartItemViewModel()
    {
        IncreaseCommand = new MvxCommand(ExecuteIncreaseCommand);
        DecreaseCommand = new MvxCommand(ExecuteDecreaseCommand, CanExecuteDecreaseCommand);
        Delete = new MvxCommand (() => {Quantity++;});
    }        

    public int Quantity
    {
        get { return quantity; }
        set
        {
            quantity = value;
            RaisePropertyChanged("Quantity");
            RaisePropertyChanged("SubTotal");
            DecreaseCommand.RaiseCanExecuteChanged();
        }
    }

    public IMvxCommand IncreaseCommand { get; set; }
    public IMvxCommand DecreaseCommand { get; set; }
    public IMvxCommand Delete { get; set; }


    private void ExecuteIncreaseCommand()
    {
         Quantity++;
    }

    private void ExecuteDecreaseCommand()
    {
        Quantity--;
    }

    private bool CanExecuteDecreaseCommand()
    {
        return Quantity > 0;
    }
}