我对Telerik.Windows.Controls DelegateCommand
我有以下设置,编译,但我更关心的是,我是否正确使用它。我已经搜索了在线文档一段时间,但找不到任何示例。
特别是,我很困惑我将如何使用CanSaveAuthorization
或基础CanExecute
,以及我将如何处理所需的对象参数。
谢谢,
public class CreateAuthorizationViewModel : ViewModelBase
{
private Authorization authorization;
private AuthorizationRepository authorizationRepository;
private DelegateCommand saveAuthorizationCommand;
public DelegateCommand SaveAuthorizationCommand
{
get
{
return saveAuthorizationCommand;
}
}
public CreateAuthorizationViewModel()
{
InitializeCommand();
}
private void InitializeCommand()
{
saveAuthorizationCommand = new DelegateCommand(SaveAuthorization, CanSaveAuthorization);
}
private void SaveAuthorization(object parameter)
{
authorizationRepository.Save();
}
private bool CanSaveAuthorization(object parameter)
{
//I would have validation logic here
return true;
}
}
答案 0 :(得分:2)
DelegateCommand
实现了ICommand
接口。这意味着它可以绑定到像Button
这样的WPF控件的Command属性。 CanExecute方法(在您的情况下为CanSaveAuthorization)可以判断是否允许执行Execute方法(在您的情况下为SaveAuthorization),否则将在视图中禁用该按钮。类型object
的参数在这里可能会有所帮助。我从未使用过Telerik的实现,但我认为这是可以在视图中设置的控件CommandParameter
属性的值。如果你有一个始终返回true的CanExecute方法,那么你也可以将它全部删除。
如果您使用Google RelayCommand
,可能会找到更多信息和示例。这可能是Telerik基于DelegateCommand
的模式。我的DelegateCommand
版本有一个没有parameter
参数的重载。然后,CanExecute方法需要viewmodel中可用的信息来确定CanExecute状态。
答案 1 :(得分:0)
这有点暂时,但您可以摆脱对InitializeCommand函数的需求:
public DelegateCommand SaveAuthorizationCommand
{
get
{
return saveAuthorizationCommand ??
(saveAuthorizationCommand = new DelegateCommand(SaveAuthorization, CanSaveAuthorization));
}
}