RelayCommand.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Windows.Input;
  3. namespace LocalizationTool.ViewModels
  4. {
  5. /// <summary>把方法包装成 ICommand 的通用实现。</summary>
  6. public class RelayCommand : ICommand
  7. {
  8. private readonly Action<object> _execute;
  9. private readonly Predicate<object> _canExecute;
  10. public RelayCommand(Action execute, Func<bool> canExecute = null)
  11. : this(_ => execute(), canExecute == null ? null : _ => canExecute()) { }
  12. public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
  13. {
  14. _execute = execute ?? throw new ArgumentNullException(nameof(execute));
  15. _canExecute = canExecute;
  16. }
  17. public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
  18. public void Execute(object parameter) => _execute(parameter);
  19. public event EventHandler CanExecuteChanged
  20. {
  21. add => CommandManager.RequerySuggested += value;
  22. remove => CommandManager.RequerySuggested -= value;
  23. }
  24. }
  25. /// <summary>带参数版本的 RelayCommand(参数在 XAML 中经 CommandParameter 传入)。</summary>
  26. public class RelayCommand<T> : ICommand
  27. {
  28. private readonly Action<T> _execute;
  29. private readonly Predicate<T> _canExecute;
  30. public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
  31. {
  32. _execute = execute ?? throw new ArgumentNullException(nameof(execute));
  33. _canExecute = canExecute;
  34. }
  35. public bool CanExecute(object parameter) => _canExecute == null || _canExecute((T)parameter);
  36. public void Execute(object parameter) => _execute((T)parameter);
  37. public event EventHandler CanExecuteChanged
  38. {
  39. add => CommandManager.RequerySuggested += value;
  40. remove => CommandManager.RequerySuggested -= value;
  41. }
  42. }
  43. }