Search code examples
c#wpfmvvmicommand

Create an Action which accepts a function with return type


I'm getting started in MVVM and WPF. I have a CreateCommand class from ICommand interface that accepts two Functions as arguments (One for Execute method and one for CanExecute method).

 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();
        }
    }

Requirement

I want to create a new command in my ViewModel like this.

        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
        }

Problem

The compilation fails and it says CanExecute expects return type to be bool
Thanks in Advance


Solution

  • It was pretty simple and straightforward. Just change the definition to

     private Func<bool> CanExecuteCommand;
    

    Thanks @LadderLogic