3

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?

Community
  • 1
  • 1
Maheep
  • 5,539
  • 3
  • 28
  • 47

3 Answers3

2

With a field-like event (which is the name for the simple form without add/remove, then when you do if(CanExecuteChanged != null) or CanExecuteChanged(this, ...), the CanExecuteChanged is referring to the backing field, which is a delegate field of type EventHandler. 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:

CommandManager.OnRequerySuggested();

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)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

I think you want CommandManager.InvalidateRequerySuggested. It forces the RequerySuggested event to be raised.

Sean
  • 60,939
  • 11
  • 97
  • 136
  • 1
    if I have say 100 commands in my code, this will re evaluate all the commands which is not good. I only want to do it for one for which this method is called – Maheep Oct 16 '12 at 10:57
1

It seems like your class inherits from the class where event is declared. Event can be directly raised only in the base class, not in inherited class.

If you want to raise it in inherited class, write the following method in your base and call it from inherited class:

protected void RaiseMyEvent()
{
if (MyEvent != null)
{
MuEvent(this, args)
}
}
Maxim Zabolotskikh
  • 3,091
  • 20
  • 21