WPF中ICommand

RelayCommand继承ICommand

public class RelayCommand : ICommand
{
    public event EventHandler CanExecuteChanged
    {
        add
        {
            if (_canExecute != null)
                CommandManager.RequerySuggested += value;
        }
        remove
        {
            if (_canExecute != null)
                CommandManager.RequerySuggested -= value;
        }
    }

    public bool CanExecute(object parameter)
    {
        return parameter != null ? _canExecute(parameter) : true;
    }

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

    }
    private Func<object, bool> _canExecute;
    private Action<object> _execute;

    public RelayCommand(Action<object> execute) : this(null, execute)
    {
        _execute = execute;
    }

    public RelayCommand(Func<object, bool> canExecute, Action<object> execute)
    {
        this._canExecute = canExecute;
        this._execute = execute;
    }

}

RelayCommand 使用方法

public RelayCommand ButtonCommand
{
    get
    {
        return new RelayCommand((o) =>
        {
            buttonCommand();
        });
    }
}
posted on 2025-02-26 15:07  每天一点点进步  阅读(9)  评论(0)    收藏  举报