private readonly Func _canExecute; private readonly Action _executeAction; /// /// Occurs when changes occur that affect whether the command should execute. /// public event EventHandler CanExecuteChanged; /// /// Initializes a new instance of the class. /// /// /// public DelegateCommand(Action executeAction, Func canExecute) { _executeAction = executeAction; _canExecute = canExecute; } /// /// Initializes a new instance of the class. /// /// public DelegateCommand(Action executeAction) { _executeAction = executeAction; _canExecute = () => true; } /// /// Raises the can execute changed. /// public void RaiseCanExecuteChanged() { EventHandler canExecuteChanged = CanExecuteChanged; if (canExecuteChanged == null) return; canExecuteChanged(this, EventArgs.Empty); } public bool CanExecute(object parameter) => _canExecute == null || _canExecute(); public void Execute(object parameter) => _executeAction(); } /// /// A command whose sole purpose is to relay its functionality to other objects by invoking delegates. /// /// public class DelegateCommand : ICommand { private readonly Func _canExecute; private readonly Action _executeAction; public event EventHandler CanExecuteChanged; /// /// Initializes a new instance of the class. /// /// /// public DelegateCommand(Action executeAction, Func canExecute) { _executeAction = executeAction; _canExecute = canExecute; } /// /// Initializes a new instance of the class. /// /// public DelegateCommand(Action executeAction) { _executeAction = executeAction; _canExecute = x => true; } /// /// Raises the can execute changed. /// public void RaiseCanExecuteChanged() { EventHandler canExecuteChanged = CanExecuteChanged; if (canExecuteChanged == null) return; canExecuteChanged(this, EventArgs.Empty); } public bool CanExecute(object parameter) { if (parameter == null) return true; T obj = ConvertParameter(parameter); return _canExecute == null || _canExecute(obj); } public void Execute(object parameter) => _executeAction(ConvertParameter(parameter)); /// /// Converts the parameter. /// /// /// /// private static T ConvertParameter(object parameter) { if (parameter == null) return default; string message = string.Format("Cannot convert {0} to {1}", parameter.GetType(), typeof(T)); T obj1 = default; if (parameter is T obj2) return obj2; if (!(parameter is string)) throw new InvalidCastException(message); MethodInfo methodInfo = (typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public)).Where(m => m.Name == "Parse" && m.GetParameters().Length == 1).FirstOrDefault(); if (methodInfo == null) return obj1; try { return (T)methodInfo.Invoke(null, new object[1] { parameter }); } catch (Exception ex) { if (ex.InnerException != null) throw ex.InnerException; throw new InvalidCastException(message); } }