Search code examples
c#wpficommand

What's the preferred way of implementing CanExecuteChanged?


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?


Solution

  • 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.