[WPF]ICommand最佳使用方法

 public class RelayCommand:ICommand
    {
        private Predicate _canExecute;
        private Action _execute;

        public RelayCommand(Predicate canExecute, Action execute)
        {
            this._canExecute = canExecute;
            this._execute = execute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    } 
  

使用:

public class MyViewModel
{
    private ICommand _doSomething;
    public ICommand DoSomethingCommand
    {
        get
        {
            if (_doSomething == null)
            {
                _doSomething = new RelayCommand(
                    p => this.CanDoSomething,
                    p => this.DoSomeImportantMethod());
            }
            return _doSomething;
        }
    }
}

 

其中,Predicate

[WPF]ICommand最佳使用方法_第1张图片[WPF]ICommand最佳使用方法_第2张图片

你可能感兴趣的:(WPF)