| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- // 事件传递类,用于传递界面的事件
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Input;
- namespace MvvmScaffoldFrame48.ViewModel.ViewModel
- {
- public class RelayCommand : ICommand
- {
- public event EventHandler CanExecuteChanged;
- private Action<object> _Excute { get; set; }
- private Predicate<object> _CanExcute { get; set; }
- public RelayCommand(Action<object> ExcuteMethod, Predicate<object> CanExcuteMethod)
- {
- _Excute = ExcuteMethod;
- _CanExcute = CanExcuteMethod;
- }
- public bool CanExecute(object parameter)
- {
- return _CanExcute(parameter);
- }
- public void Execute(object parameter)
- {
- _Excute(parameter);
- }
- }
- public class RelayCommand<T> : ICommand
- {
- private readonly Action<T> _execute;
- private readonly Predicate<T> _canExecute;
- // 定义 CanExecuteChanged 事件
- public event EventHandler CanExecuteChanged;
- public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
- {
- _execute = execute ?? throw new ArgumentNullException(nameof(execute));
- _canExecute = canExecute;
- }
- // 判断命令是否可以执行
- public bool CanExecute(object parameter)
- {
- return _canExecute == null || _canExecute((T)parameter);
- }
- // 执行命令逻辑
- public void Execute(object parameter)
- {
- _execute((T)parameter);
- }
- // 手动触发 CanExecuteChanged 事件(用于通知 UI 刷新命令状态)
- public void RaiseCanExecuteChanged()
- {
- CanExecuteChanged?.Invoke(this, EventArgs.Empty);
- }
- }
- }
|