简体   繁体   English

CanExecute应该做什么?

[英]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. 如果我们在执行的方法中执行其他数据验证,那么拥有一个can execute方法似乎是多余的。

The way that I see it is that there is a distinction of whether something CAN happen and if something SHOULD happen. 我看到的方式是,是否可以发生某些事情以及是否应该发生某些事情存在区别。

An example of this can be a save button or something. 例如保存按钮或类似的东西。 The user may not have rights to save an entity so the action CAN'T happen. 用户可能无权保存实体,因此操作不会发生。

If the user does have rights, all of the required fields may not be filled in so it SHOULDN'T happen. 如果用户确实拥有权限,则可能没有填写所有必填字段,因此应该不会发生。

Its in the semantics. 它的语义。

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. 如果命令的逻辑假定必须满足某些条件,则必须执行这些命令,否则CanExecute必须检查这些条件。

Otherwise, CanExecute must return true. 否则, CanExecute必须返回true。

It doesn't matter, what is the nature of conditions, but you should note, that long running checks may hit UI thread performance. 条件的性质没关系,但是您应该注意,长时间运行的检查可能会影响UI线程的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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