Open singba opened 4 years ago
using System; using System.Windows.Input; namespace ConfuserEx { public class RelayCommand : RelayCommand<object>, ICommand { public RelayCommand(Action execute) : base((p) => execute()) { } public RelayCommand(Action execute, Func<bool> canExecute) :base((p)=>execute(),(p)=>canExecute()) { } } public class RelayCommand<T> : ICommand { #region Fields private Func<T, bool> _canExecute; private Action<T> _execute; private bool _IsExecuting = false; #endregion // Fields #region Constructors public RelayCommand(Action<T> execute) : this(execute, null) { } public RelayCommand(Action<T> execute, Func<T, bool> canExecute) { ResetActions(execute, canExecute); } #endregion // Constructors #region ICommand Members public bool CanExecute(object parameter) { return _canExecute == null ? true : ((!_IsExecuting) && _canExecute((T)parameter)); } public event EventHandler CanExecuteChanged { add { System.Windows.Input.CommandManager.RequerySuggested += value; } remove { System.Windows.Input.CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { try { if (_IsExecuting) return; _IsExecuting = true; RaiseCanExecuteChanged(); _execute((T)parameter); } catch (Exception) { throw; } finally { _IsExecuting = false; RaiseCanExecuteChanged(); } } #endregion public void ResetActions(Action<T> execute, Func<T, bool> canExecute) { if (execute != null) { _execute = execute; } if (canExecute != null) { _canExecute = canExecute; } } public void RaiseCanExecuteChanged() { System.Windows.Input.CommandManager.InvalidateRequerySuggested(); } } }