Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement ICommand without parameters

In my project, i'd like to use MVVM (& Commands). I've started learning about commands and implementation of ICommand.

I'd like to create implementation of ICommand without parameters. (To trigger loading of data/flushing of data etc. - I don't need any parameters to do it, so it just seems natural to try and create command without parameters)

This is the code I'm using:

using System.Windows.Input;

public class NoParameterCommand : ICommand
{
    private Action executeDelegate = null;
    private Func<bool> canExecuteDelegate = null;
    public event EventHandler CanExecuteChanged = null;

    public NoParameterCommand(Action execute)
    {
        executeDelegate = execute;
        canExecuteDelegate = () => { return true; };
    }
    public NoParameterCommand(Action execute, Func<bool> canExecute)
    {
        executeDelegate = execute;
        canExecuteDelegate = canExecute;
    }

    public bool CanExecute()
    {
        return canExecuteDelegate();
    }
    public void Execute()
    {
        if (executeDelegate != null)
        {
            executeDelegate();
        }
    }
}

But i got errors about not implementing the ICommand interface in the right manner ('XXX.YYYY.NoParameterCommand' does not implement interface member 'System.Windows.Input.ICommand.Execute(object)')

So I thought about doing it like this instead:

(Added the parameters that were missing from CanExecute and Execute)

public class NoParameterCommand : ICommand
{
    ...omitted - no changes here...

    public bool CanExecute(object parameter) //here I added parameter
    {
        return canExecuteDelegate();
    }
    public void Execute(object parameter)    //and here
    {
        if (executeDelegate != null)
        {
            executeDelegate();
        }
    }
}
  1. IS THIS A GOOD WAY TO DO IT?
  2. SHOULD I USE ANOTHER WAY? (IF SO, WHAT SHOULD I DO INSTEAD?)
like image 723
mishan Avatar asked Oct 14 '13 12:10

mishan


1 Answers

  1. This is a good way to do it.
  2. No, you should not use another way.

Additional suggestions:

Thinking about this again, I would improve your architecture by introducing an additional hierarchy level where CanExecute() and Execute() are abstract. From that class, derive your command class that invokes delegates.

This way, you can decide later on whether you want to supply your logic for your parameterless commands via delegates or via subclassing your base command class.

like image 195
O. R. Mapper Avatar answered Oct 02 '22 22:10

O. R. Mapper