While copying code for RelayCommand from Josh Smith article I copied following code
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
Then after reading this answer on SO I also copied in my class following code from DelegateCommand class of Prism.
protected void NotifyCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
But his gives me an error in NotifyCanExecuteChanged method
The event ‘CanExecuteChanged’ can only appear on the left hand side of += or -=
This error is not coming if I remove the add and remove overload from event. Can someone please help me understand the reason behind this?
With a field-like event (which is the name for the simple form without
add/remove, then when you doif(CanExecuteChanged != null)orCanExecuteChanged(this, ...), theCanExecuteChangedis referring to the backing field, which is a delegate field of typeEventHandler. You can invoke a delegate field. However, that is not the case in your example, because there is no obvious thing to invoke. There certainly isn’t a local field, and the forwarded event (CommandManaged.RequerySuggested) does not intrinsically expose any “invoke” capability.Basically, for that to work you would need access to an invoke mechanism. Most commonly, I would expect that to take the form of:
but if there is a method that invokes this event (and there doesn’t need to be), it could be called anything.
(the
On*is a common pattern for a “raise this event” API, doubly-so if it is polymorphic)