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();
}
}
}
- IS THIS A GOOD WAY TO DO IT?
- SHOULD I USE ANOTHER WAY? (IF SO, WHAT SHOULD I DO INSTEAD?)