RelayComand.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // 事件传递类,用于传递界面的事件
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Input;
  8. namespace MvvmScaffoldFrame48.ViewModel.ViewModel
  9. {
  10. public class RelayCommand : ICommand
  11. {
  12. public event EventHandler CanExecuteChanged;
  13. private Action<object> _Excute { get; set; }
  14. private Predicate<object> _CanExcute { get; set; }
  15. public RelayCommand(Action<object> ExcuteMethod, Predicate<object> CanExcuteMethod)
  16. {
  17. _Excute = ExcuteMethod;
  18. _CanExcute = CanExcuteMethod;
  19. }
  20. public bool CanExecute(object parameter)
  21. {
  22. return _CanExcute(parameter);
  23. }
  24. public void Execute(object parameter)
  25. {
  26. _Excute(parameter);
  27. }
  28. }
  29. public class RelayCommand<T> : ICommand
  30. {
  31. private readonly Action<T> _execute;
  32. private readonly Predicate<T> _canExecute;
  33. // 定义 CanExecuteChanged 事件
  34. public event EventHandler CanExecuteChanged;
  35. public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
  36. {
  37. _execute = execute ?? throw new ArgumentNullException(nameof(execute));
  38. _canExecute = canExecute;
  39. }
  40. // 判断命令是否可以执行
  41. public bool CanExecute(object parameter)
  42. {
  43. return _canExecute == null || _canExecute((T)parameter);
  44. }
  45. // 执行命令逻辑
  46. public void Execute(object parameter)
  47. {
  48. _execute((T)parameter);
  49. }
  50. // 手动触发 CanExecuteChanged 事件(用于通知 UI 刷新命令状态)
  51. public void RaiseCanExecuteChanged()
  52. {
  53. CanExecuteChanged?.Invoke(this, EventArgs.Empty);
  54. }
  55. }
  56. }