| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- using System;
- using System.Windows.Input;
- namespace LocalizationTool.ViewModels
- {
- /// <summary>把方法包装成 ICommand 的通用实现。</summary>
- public class RelayCommand : ICommand
- {
- private readonly Action<object> _execute;
- private readonly Predicate<object> _canExecute;
- public RelayCommand(Action execute, Func<bool> canExecute = null)
- : this(_ => execute(), canExecute == null ? null : _ => canExecute()) { }
- public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
- {
- _execute = execute ?? throw new ArgumentNullException(nameof(execute));
- _canExecute = canExecute;
- }
- public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
- public void Execute(object parameter) => _execute(parameter);
- public event EventHandler CanExecuteChanged
- {
- add => CommandManager.RequerySuggested += value;
- remove => CommandManager.RequerySuggested -= value;
- }
- }
- /// <summary>带参数版本的 RelayCommand(参数在 XAML 中经 CommandParameter 传入)。</summary>
- public class RelayCommand<T> : ICommand
- {
- private readonly Action<T> _execute;
- private readonly Predicate<T> _canExecute;
- public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
- {
- _execute = execute ?? throw new ArgumentNullException(nameof(execute));
- _canExecute = canExecute;
- }
- public bool CanExecute(object parameter) => _canExecute == null || _canExecute((T)parameter);
- public void Execute(object parameter) => _execute((T)parameter);
- public event EventHandler CanExecuteChanged
- {
- add => CommandManager.RequerySuggested += value;
- remove => CommandManager.RequerySuggested -= value;
- }
- }
- }
|