using System; using System.Diagnostics; using System.Windows.Input; namespace MVVM { /// /// Class used for function calls in view models. /// public class RelayCommand : ICommand { readonly Action _execute; readonly Predicate _canExecute; /// /// Creates a new command that can always execute. /// /// public RelayCommand(Action execute) : this(execute, null) { } /// /// Creates a new command. /// /// /// public RelayCommand(Action execute, Predicate canExecute) { if (execute == null) throw new ArgumentNullException(nameof(execute)); _execute = execute; _canExecute = canExecute; } /// /// Executes the Action. /// /// public void Execute(object parameter) { _execute(parameter); } /// /// Used to check whether command can be executed. /// /// /// True if command can be executed. [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute == null || _canExecute(parameter); } /// /// Raised when value of CanExecute changed. /// public event EventHandler CanExecuteChanged { add { if (_canExecute != null) CommandManager.RequerySuggested += value; } remove { if (_canExecute != null) CommandManager.RequerySuggested -= value; } } /// /// Must be called when CanExecute should be reevaluated. /// public void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } } }