RelayCommand class
/// <summary>
/// Interface for commands to use in MVVM Pattern. It implements ICommand interface.
/// </summary>
public class RelayCommand : ICommand
{
readonly Action<object> execute;
readonly Func<object, bool> canExecute;
/// <summary>
/// CanExecuteChanged event handler.
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
if (canExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (canExecute != null)
CommandManager.RequerySuggested -= value;
}
}
/// <summary>
/// Constructor takes Execute and CanExecute events to register in CommandManager.
/// </summary>
/// <param name="execute"> Execute method as action. </param>
/// <param name="canExecute"> CanExecute method as return boolean type. </param>
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// CanExecute method.
/// </summary>
/// <param name="parameter"> Method parameter. </param>
/// <returns> Return true if can execute, else false. </returns>
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
/// <summary>
/// Execute method.
/// </summary>
/// <param name="parameter"> Method parameter. </param>
public void Execute(object parameter)
{
this.execute(parameter);
}
/// <summary>
/// InvalidateCanExecute method forces CanExecute evaluation.
/// </summary>
public static void InvalidateCanExecute()
{
CommandManager.InvalidateRequerySuggested();
}
}