I was trying to understand the ICommand interface. I built an application with a button that uses a class called RelayCommand which inherits from ICommand. The class looks like this:
class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
if(parameter != null)
{
_action(parameter);
}
else
{
_action("Hello World");
}
}
//We need to include CanExecuteChange when using the Interface ICommand
//In this case it doesn't actually do anything.
public event EventHandler CanExecuteChanged;
}
Everytime I trace the the function, I hit the CanExecute method, but nowwhere in my code am I calling this method. I create a RelayCommand instance like so:
Btn_AcceptedAnswer = new RelayCommand(new Action<object>(AcceptedAnswer_OnClick));
So my question is, when RelayCommand is initiated, how does it know to run CanExecute() and Execute(), and when does it run these? I know how to implement an event, I am just trying to understand how it works.