c# - 创建一个接受具有返回类型的函数的操作

标签 c# wpf mvvm icommand

我开始使用 MVVM 和 WPF。我有一个 CreateCommand来自 ICommand 的类(class)接受两个函数作为参数的接口(interface)(一个用于 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 期望返回类型为 bool

提前致谢

最佳答案

这非常简单明了。
只需将定义更改为

 private Func<bool> CanExecuteCommand;

谢谢@LadderLogic

关于c# - 创建一个接受具有返回类型的函数的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998658/

相关文章:

c# - 如何在C#中记录Leap Motion的帧以进行手震跟踪?

wpf - 更改 WPFToolkit 图表控件的默认颜色

wpf - WPF 中的简单 CRUD 应用

c# - MVVM Silverlight 数据网格 : Binding Columns Collection

c# - 项目类型不允许添加新的 "Web User Control"

c# - 有什么方法可以判断值来自哪个属性?

c# - 如何检查扩展方法中类型中是否存在属性?

wpf - 使用 ViewModel WPF 从 Codehind 执行方法

javascript - 如何使用knockout js引用当前元素?

java - 在屏幕中的不同 Fragment 之间共享一个 ViewModel 实例