简体   繁体   中英

Why can't I raise or call event if I have overloaded add and remove in C#

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 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)

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

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)
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM