WSC
WSC

Reputation: 993

RelayCommand CanExecute not working when parameter passed with async lambda

I have the following command which works:

private ICommand _AddNewCommand;
public ICommand AddNewCommand
{
    get
    {
        if (_AddNewCommand == null)
        {
            _AddNewCommand = new RelayCommand(async () =>
                                              {
                                                  await AddNewAsync();
                                              }, AddNewCommand_CanExecute);
        }
        return _AddNewCommand;
    }
}

The button bound to this is correctly enabled/disabled according to the AddNewCommand_CanExecute method result.

However, if I want to pass some parameter into my AddNewAsync() method I do this:

 _AddNewCommand = new RelayCommand<object>(async obj =>
                                          {
                                              await AddNewAsync(obj);
                                          }, AddNewCommand_CanExecute());

Note that AddNewCommand_CanExecute has to be changed to AddNewCommand_CanExecute().

However, when I do this, the bound button is always enabled even though AddNewCommand_CanExecute() should be returning false (given that it hasn't changed between the two).

What's going on here?

Upvotes: 0

Views: 636

Answers (1)

mm8
mm8

Reputation: 169160

You are using the overload of RelayCommand<T> that accepts a keepTargetAlive parameter of type bool.

You should use the one that accepts a Func<T, bool> predicate:

_AddNewCommand = new RelayCommand<object>(async obj =>
{
    await AddNewAsync(obj);
}, _ => AddNewCommand_CanExecute());

Upvotes: 1

Related Questions