创建一个 Action 接受 return 类型的函数
Create an Action which accepts a function with return type
我开始使用 MVVM 和 WPF。我有一个来自 ICommand
接口的 CreateCommand
class,它接受两个函数作为参数(一个用于 Execute 方法,一个用于 CanExecute
方法)。
class CreateCommand: ICommand
{
private Action ExecuteCommand;
private Action CanExecuteCommand;
public event EventHandler CanExecuteChanged;
public CreateCommand(Action executeAction,Action canExecuteAction)
{
ExecuteCommand = executeAction;
CanExecuteCommand = canExecuteAction;
}
public bool CanExecute(object parameter)
{
// gives error that the function CanExecute expects return type to be bool
return CanExecuteCommand();
}
public void Execute(object parameter)
{
ExecuteCommand();
}
}
要求
我想像这样在我的 ViewModel 中创建一个新命令。
private ICommand _AddItemCmd;
public ICommand AddItemCmd
{
get
{
if (_AddItemCmd == null)
_AddItemCmd = new CreateCommand(AddItemToList,IsProductItemEmpty);
return _AddItemCmd;
}
set
{
_AddItemCmd = value;
}
}
public void AddItemToList(){
//My blah blah code
}
public bool IsProductItemEmpty(){
//return true
//OR
//return false
}
问题
编译失败,它说 CanExecute expects return type to be bool
提前致谢
这非常简单明了。
只需将定义更改为
private Func<bool> CanExecuteCommand;
感谢@LadderLogic
我开始使用 MVVM 和 WPF。我有一个来自 ICommand
接口的 CreateCommand
class,它接受两个函数作为参数(一个用于 Execute 方法,一个用于 CanExecute
方法)。
class CreateCommand: ICommand
{
private Action ExecuteCommand;
private Action CanExecuteCommand;
public event EventHandler CanExecuteChanged;
public CreateCommand(Action executeAction,Action canExecuteAction)
{
ExecuteCommand = executeAction;
CanExecuteCommand = canExecuteAction;
}
public bool CanExecute(object parameter)
{
// gives error that the function CanExecute expects return type to be bool
return CanExecuteCommand();
}
public void Execute(object parameter)
{
ExecuteCommand();
}
}
要求
我想像这样在我的 ViewModel 中创建一个新命令。
private ICommand _AddItemCmd;
public ICommand AddItemCmd
{
get
{
if (_AddItemCmd == null)
_AddItemCmd = new CreateCommand(AddItemToList,IsProductItemEmpty);
return _AddItemCmd;
}
set
{
_AddItemCmd = value;
}
}
public void AddItemToList(){
//My blah blah code
}
public bool IsProductItemEmpty(){
//return true
//OR
//return false
}
问题
编译失败,它说 CanExecute expects return type to be bool
提前致谢
这非常简单明了。 只需将定义更改为
private Func<bool> CanExecuteCommand;
感谢@LadderLogic