Search code examples
c#wpfcommandbindingcanexecute

What should go in CanExecute?


I think that there is a specific answer to this.

If I have a command binding

private bool CanExecute(Object args){
  // Should this just be null checks?
  // Should it also contain logic? 
  // example:

  return this.SelectedObject != null;

  // or 

  return this.SelectedObject != null && this.SelectedObject.Status == 1;
}

private void Executed(Object args){

  //Or should logic be reserved for the Executed command

  if(this.SelectedObject.Status == 1)
     //Do stuff
  else
     //Don't do stuff
}

It seems redundant to have a can execute method if we do additional data validation within the executed method.


Solution

  • if the logic of your command assumes, that it must not be executed, when some conditions have met, then CanExecute have to check these conditions.

    Otherwise, CanExecute must return true.

    It doesn't matter, what is the nature of conditions, but you should note, that long running checks may hit UI thread performance.