Reputation: 335
I am working on a Xamarin.Android application and I am using MvvmCross. Here in my code DecreaseCommand
is not working:
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;
}
}
I suspect that CanExecuteDecreaseCommand
is not firing, what could be wrong in this code?
Upvotes: 4
Views: 909
Reputation: 4995
You forgot to call RaiseCanExecuteChanged
when you update your Quantity
property.
Plus, you don't need to set a CanExecute
that always returns true:
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;
}
}
Upvotes: 4