using System; using System.Windows.Input; namespace MVVM_DEMO.Commands { /// /// A command whose sole purpose is to relay its functionality to other objects by invoking delegates. /// The default return value for the CanExecute method is 'true'. /// public class RelayCommand : ICommand { private readonly Action _execute; private readonly Func? _canExecute; /// /// Occurs when changes occur that affect whether or not the command should execute. /// public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } /// /// Creates a new command that can always execute. /// /// The execution logic. public RelayCommand(Action execute) : this(execute, null) { } /// /// Creates a new command. /// /// The execution logic. /// The execution status logic. public RelayCommand(Action execute, Func? canExecute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } /// /// Determines whether this command can execute in its current state. /// /// Data used by the command. If the command does not require data to be passed, this object can be set to null. /// true if this command can be executed; otherwise, false. public bool CanExecute(object? parameter) { return _canExecute == null || _canExecute(parameter); } /// /// Executes the command. /// /// Data used by the command. If the command does not require data to be passed, this object can be set to null. public void Execute(object? parameter) { _execute(parameter); } } }