I am new to MVVM and I would like to create simple command button that will be enabled if any of the items in list is selected and that will add listitem selected to the favorite list. Here is my AddCommand implementation:
class AddFavCommand : ICommand
{
private readonly Action _favAction;
private readonly bool _canExecute;
public AddFavCommand()
{
}
public AddFavCommand(Action favAction, bool canExecute)
{
_favAction = favAction;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_favAction();
}
}
In my View Model I have public property AddFavCommand in order to do binding with my view:
private AddFavCommand _addFavCommand;
private bool _canAddFavExecute;
public ICommand AddFavCommand
{
get
{
if (_addFavCommand == null)
{
_addFavCommand = new AddFavCommand(AddFav, _canAddFavExecute);
}
return _addFavCommand;
}
}
and for now I have simple function just to check if command will work:
private void AddFav()
{
MessageBox.Show("Add");
}
so this part works perfectly without implementing canExecute property. But now I want button to be disabled when list item in my list is not selected. I have a property:
CurrentItem
that is binded to List Item and it will be null if item is not selected. My question is how to trigger button to be disabled when item is not selected. I tried to adding:
private void AddFav()
{
MessageBox.Show("Add");
_canAddFavExecute = CurrentItem != null; // to my function, but my button always stays disabled.
}
Thanks
but it doesn't work.- Too vague. What does not work? what behavior does it have versus what you expect. Do you get any errors? Please be specific. Also, that should really beCurrentItem != nulland be placed in the property setter - Federico Berasategui