I am using a couple of Buttons bound to RelayCommands initialized with CanExecute delegates.
RelayCommand DeleteCommand;
bool CanDelete()
{
return BoolProp1 && BoolProp2;
}
...
DeleteCommand = new RelayCommand(Delete, CanDelete);
BoolProp1 and BoolProp2 are regular properties with setters correctly raising PropertyChanged, but as we all know, this is not enough to make SL reevaluate CanExecute on commands. That's why i also call Delete.RaiseCanExecuteChanged() in both setters.
All this works fine (buttons are disabled and enabled properly) up to some point, where is all stops. At that point, calling Delete.RaiseCanExecuteChanged() no longer fires my breakpoints in CanDelete() and buttons forever stay the way they were.
I spend 2 hours trying to isolate the exact cause with no effect. I suspect multiple RaiseCanExecuteChanged() calls during single "binding iteration" somehow break the mechanism.
Any hints? I'm already considering using an additional IsExecutable field refreshed through INotifyPropertyChanged...
UPDATE
RelayCommand is actually GalaSoft.MvvmLight.Command.RelayCommand from MVVM Light Toolkit. ILSpy shows a pretty trivial implementation of ICommand:
public bool CanExecute(object parameter)
{
return this._canExecute == null || this._canExecute.Invoke();
}
public void RaiseCanExecuteChanged()
{
EventHandler canExecuteChanged = this.CanExecuteChanged;
if (canExecuteChanged != null)
{
canExecuteChanged.Invoke(this, EventArgs.Empty);
}
}
with _canExecute being a Func<bool> set once to the value passed to constructor.
I am still working to minimally reproduce the issue.
UPDATE
See my answer.
RelayCommandExwas my failed attempt to deal with this (tried caching CanExecute() value and not firing CanExecuteChanged if not needed). - Jacek Gorgoń