0

Here's the code I'm working with, the only change I've made there is added [CallerMemberName] attribute in void Changed([CallerMemberName] string name = "") method like that. In an article yesterday, I've read that instead of doing

    public event EventHandler CanExecuteChanged 
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

I could replace this part:

    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

with a ; and add a function to handle CanExecuteChanged in Command class like this:

    public void Evaluate() => CanExecuteChanged?.Invoke(null, EventArgs.Empty);

and call the Evaluate method inside the setters of FirstName and LastName properties of Person class. I've tested the app with both add/remove and Evaluate and both works.

Which of these would be more efficient?

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
  • 1
    You should use the simpler form in most cases. However, in the above case, your custom code delegate event add and remove to a command manager so you probably want to raise events from that manager too so delegation would be required. – Phil1970 Oct 12 '19 at 16:15

1 Answers1

0

In this piece of code

public event EventHandler CanExecuteChanged
{
    add => CommandManager.RequerySuggested += value;
    remove => CommandManager.RequerySuggested -= value;
}

RequirySuggested event is required for proper work of CommandManager.InvalidateRequerySuggested method.

This method is used for invalidate the command bindings and update CanExecute for all commands. You did almost the same manually using CanExecuteChanged?.Invoke(null, EventArgs.Empty); for your Person class. But for some cases CommandManager.InvalidateRequerySuggested is still needed, for example when you need to update command binding outside of Person class or from other ViewModel.

There is also existing SO thread with different opinions regarding your question.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
  • then obviously the `Evaluate` method is redundant and there's no point in having one such in `Command`class since it works fine with `add/remove`. –  Oct 12 '19 at 17:15
  • 1
    `CommandManager.InvalidateRequerySuggested` and `add/remove` will update all commands bindings, with your invocation you have to it manually all the time. First option sounds more convenient – Pavel Anikhouski Oct 12 '19 at 17:39
  • now you have to call `CommandManager.InvalidateRequerySuggested` everywhere where you would call `Evaluate()`. I dont see the difference. – Firo Mar 15 '22 at 14:35