2017. 4. 18. 10:38

Command Pattern



선언

    public class DelegateCommand : ICommand
    {
        private Action<object> _execute;
        private Predicate<object> _canExecute;

        public DelegateCommand(Action<object> execute)
               : this(execute, null)
        {
        }

        public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

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

        public event EventHandler CanExecuteChanged = delegate { };

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

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }
    }


구현

        private ICommand _addCommand;
        public ICommand AddCommand
        {
            get
            {
                return _addCommand ??
                    (_addCommand = new DelegateCommand(
                        p => { 
                            // Add 로직 
                        },
                        p => { // Command 사용여부 
                                  return true; 
                        }
                    ));
            }
        }




Xaml

<Button Content="Add" Command={Binding AddCommand} />

<Window.InputBidings>
    <KeyBinding Key="A"
                       Modifiers="Control"
                       Command={Binding AddCommand} />
</Window.InputBidings>




Posted by CoolDragon