To bind a command of a button you need to bind a property that is an implementation of an ICommand. AnICommand is composed by:
- event EventHandler CanExecuteChanged;
- bool CanExecute(object parameter);
- void Execute(object parameter);
CanExecute will determine whether the command can be executed or not. If it returns false the button will be disabled on the interface.
Execute runs the command logic.
With a simple implementation of ICommand I can create the following:
- public class NormalCommand : ICommand
- {
- public event EventHandler CanExecuteChanged;
- public bool CanExecute(object parameter)
- {
- throw new NotImplementedException();
- }
- public void Execute(object parameter)
- {
- throw new NotImplementedException();
- }
- }
- public class RelayCommand : ICommand
- {
- private Action<object> execute;
- private Func<object, bool> canExecute;
- public event EventHandler CanExecuteChanged
- {
- add { CommandManager.RequerySuggested += value; }
- remove { CommandManager.RequerySuggested -= value; }
- }
- public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
- {
- this.execute = execute;
- this.canExecute = canExecute;
- }
- public bool CanExecute(object parameter)
- {
- return this.canExecute == null || this.canExecute(parameter);
- }
- public void Execute(object parameter)
- {
- this.execute(parameter);
- }
- }
- var cmd1 = new RelayCommand(o => { /* do something 1 */ }, o => true);
- var cmd2 = new RelayCommand(o => { /* do something 2 */ }, o => true);
Comments
Post a Comment