Pages

Sunday, July 21, 2013

Delegate Command class for WPF Application

public class DelegateCommand : ICommand

         {

                 private readonly Action executeMethod = delegate { };

 

                 private readonly Func<bool> canExecuteMethod;

 

                 public DelegateCommand(Action executeMethod)

                          : this(executeMethod, null)

                 {

                 }

 

                 public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)

                 {

                          this.executeMethod = executeMethod;

                          this.canExecuteMethod = canExecuteMethod;

                 }

 

                 public bool CanExecute(object parameter)

                 {

                          return canExecuteMethod != null ? canExecuteMethod() : true;

                 }

 

                 public void Execute(object parameter)

                 {

                          executeMethod();

                 }

 

                 public event EventHandler CanExecuteChanged;

         }

 

         public class DelegateCommand<T> : ICommand

         {

                 private readonly Action<T> executeMethod = delegate { };

 

                 private readonly Func<T, bool> canExecuteMethod;

 

                 public DelegateCommand(Action<T> executeMethod)

                          : this(executeMethod, null)

                 {

                 }

 

                 public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)

                 {

                          this.executeMethod = executeMethod;

                          this.canExecuteMethod = canExecuteMethod;

                 }

 

                 public bool CanExecute(object parameter)

                 {

                          T tobj = (T)parameter;

                          return canExecuteMethod != null ? canExecuteMethod(tobj) : true;

                 }

 

                 public void Execute(object parameter)

                 {

                          T tobj = (T)parameter;

                          executeMethod(tobj);

                 }

 

                 public event EventHandler CanExecuteChanged;

         }