Posted By

bokkers on 03/31/09


Tagged

commands WPF MVVM ICommand


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


RelayCommand class


 / Published in: C#
 

This class can be found in this article on MSDN: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090051 It makes it possible to add WPF-commands to your ViewModel classes without the need for using nested classes for each command.

  1. public class RelayCommand : ICommand
  2. {
  3. #region Fields
  4.  
  5. readonly Action<object> _execute;
  6. readonly Predicate<object> _canExecute;
  7.  
  8. #endregion // Fields
  9.  
  10. #region Constructors
  11.  
  12. public RelayCommand(Action<object> execute)
  13. : this(execute, null)
  14. {
  15. }
  16.  
  17. public RelayCommand(Action<object> execute, Predicate<object> canExecute)
  18. {
  19. if (execute == null)
  20. throw new ArgumentNullException("execute");
  21.  
  22. _execute = execute;
  23. _canExecute = canExecute;
  24. }
  25. #endregion // Constructors
  26.  
  27. #region ICommand Members
  28.  
  29. [DebuggerStepThrough]
  30. public bool CanExecute(object parameter)
  31. {
  32. return _canExecute == null ? true : _canExecute(parameter);
  33. }
  34.  
  35. public event EventHandler CanExecuteChanged
  36. {
  37. add { CommandManager.RequerySuggested += value; }
  38. remove { CommandManager.RequerySuggested -= value; }
  39. }
  40.  
  41. public void Execute(object parameter)
  42. {
  43. _execute(parameter);
  44. }
  45.  
  46. #endregion // ICommand Members
  47. }
  48.  
  49. // To use this class within your viewmodel class:
  50. RelayCommand _myCommand;
  51. public ICommand MyCommand
  52. {
  53. get
  54. {
  55. if (_myCommand == null)
  56. {
  57. _myCommand = new RelayCommand(p => this.DoMyCommand(p),
  58. p => this.CanDoMyCommand(p) );
  59. }
  60. return _myCommand;
  61. }
  62. }

Report this snippet  

You need to login to post a comment.