123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Input;
- namespace athosRT.tool
- {
- public class CommandBase : ICommand
- {
- private readonly Action<object> _commandpara;
- private readonly Action _command;
- private readonly Func<bool> _canExecute;
- public CommandBase(Action command, Func<bool> canExecute = null)
- {
- if (command == null)
- {
- throw new ArgumentNullException();
- }
- _canExecute = canExecute;
- _command = command;
- }
- public CommandBase(Action<object> commandpara, Func<bool> canExecute = null)
- {
- if (commandpara == null)
- {
- throw new ArgumentNullException();
- }
- _canExecute = canExecute;
- _commandpara = commandpara;
- }
- public bool CanExecute(object parameter)
- {
- return _canExecute == null || _canExecute();
- }
- public event EventHandler CanExecuteChanged
- {
- add { CommandManager.RequerySuggested += value; }
- remove { CommandManager.RequerySuggested -= value; }
- }
- public void Execute(object parameter)
- {
- if (parameter != null)
- {
- _commandpara(parameter);
- }
- else
- {
- if (_command != null)
- {
- _command();
- }
- else if (_commandpara != null)
- {
- _commandpara(null);
- }
- }
- }
- }
- public class DelegateCommand : ICommand
- {
- // 定义一个名为SimpleEventHandler的委托,两个参数,一个object类,一个是自定义的DelegateCommandEventArgs类
- public delegate void SimpleEventHandler(object sender, DelegateCommandEventArgs e);
- // handler是方法,别忘了,委托是用于定义方法的类
- private SimpleEventHandler handler;
- private bool isEnabled = true;
- public DelegateCommand(SimpleEventHandler handler)
- {
- this.handler = handler;
- }
- public void Execute(object parameter)
- {
- this.handler(this, new DelegateCommandEventArgs(parameter));
- }
- public bool CanExecute(object parameter)
- {
- return this.isEnabled;
- }
- public event EventHandler CanExecuteChanged;
- public bool IsEnabled
- {
- get { return this.isEnabled; }
- set
- {
- this.isEnabled = value;
- this.OnCanExecuteChanged();
- }
- }
- private void OnCanExecuteChanged()
- {
- if (this.CanExecuteChanged != null)
- this.CanExecuteChanged(this, EventArgs.Empty);
- }
- }
- public class DelegateCommandEventArgs : EventArgs
- {
- private object parameter;
- public DelegateCommandEventArgs(object parameter)
- {
- this.parameter = parameter;
- }
- public object Parameter
- {
- get { return this.parameter; }
- }
- }
- }
|