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.
PEBKAC. My framework in certain cases ran the code
DeleteCommand = new RelayCommand(Delete, CanDelete);
more then once, overwriting commands that were actually bound to view with new instances.
If somebody has this problem - make sure you're calling RelayCommand.RaiseCanExecuteChanged()
on the same instance that the view is bound to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With