[英]Why CanExecute only get called when it's initialized in the constructor of the view model?
I have a Command
property, with this definition in the view model:我有一个
Command
属性,在视图模型中有这个定义:
public RelayCommand SaveCommand => new RelayCommand(OnSave, CanSave);
whenever the ErrorsChanged
of the INotifyDataErrorInfo
is fired, RaiseCanExecuteChanged
is called in the RelayCommand
class, to enable/disable the button:每当
ErrorsChanged
中的INotifyDataErrorInfo
被激发, RaiseCanExecuteChanged
是所谓的RelayCommand
类,启用/禁用按钮:
public void RaiseCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
the two delegates of the command are set in the constructor:命令的两个委托在构造函数中设置:
public RelayCommand(Action executeMethod, Func<bool> canExecuteMethod)
{
_TargetExecuteMethod = executeMethod;
_TargetCanExecuteMethod = canExecuteMethod;
}
but when the error state changed (when RaiseCanExecuteChanged
is called) the CanSave
method doesn't get called, after a while I changed the Command
initialization way to be set in the constructor instead:但是当错误状态改变时(当
RaiseCanExecuteChanged
被调用时) CanSave
方法不会被调用,过了一会儿我改变了在构造函数中设置的Command
初始化方式:
public AddEditCustomerViewModel()
{
SaveCommand = new RelayCommand(OnSave, CanSave);
}
public RelayCommand SaveCommand {get;}
and it works!它有效! but why?
但为什么?
When you initialize the SaveCommad
in the view model's constructor, it only run once when the view model is initialized, but When you define SaveCommand
using:当您在视图模型的构造函数中初始化
SaveCommad
时,它只会在视图模型初始化时运行一次,但是当您使用以下命令定义SaveCommand
:
public RelayCommand SaveCommand => new RelayCommand(OnSave, CanSave);
You are actually doing:你实际上是在做:
public RelayCommand SaveCommand {
get {
return new RelayCommand(OnSave, CanSave);
}
}
In such case Whenever the getter of SaveCommand
is called, it returns a new instance of RelayCommand
.在这种情况下,每当
SaveCommand
的 getter 被调用时,它都会返回一个RelayCommand
的新实例。 So when the RaiseCanExecuteChanged
is called, it may not be the same object that's currently binding to the UI, hence failed to update the state因此,当调用
RaiseCanExecuteChanged
时,它可能不是当前绑定到 UI 的同一对象,因此无法更新状态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.