Using ICommands in MVVM

I've created my own generic type DelegateCommand to illustrate my implementation. You will notice that my actions and predicates take an object. This allows me to pass an object in and CommandParameter. I'll show a XAML fragment first and then the DelegateCommand.

   1 ...
   2 <Button Content="Label" Command="{Binding DelegateCommand}" CommandParameter="String I want to pass in" />
   3 ...

   1 using System;
   2 using System.Windows.Input; //for ICommand
   3 
   4 namespace GeneralEducationImporter.Model
   5 {
   6     public class DelegateCommand : ICommand
   7     {
   8         private readonly Predicate<object> _canExecute;
   9         private readonly Action<object> _execute;
  10 
  11         public event EventHandler CanExecuteChanged;
  12 
  13         public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
  14         {
  15             _execute = execute;
  16             _canExecute = canExecute;
  17         }
  18 
  19         public bool CanExecute(object parameter)
  20         {
  21             return _canExecute == null || _canExecute(parameter);
  22         }
  23 
  24         public void Execute(object parameter)
  25         {
  26             _execute(parameter);
  27         }
  28 
  29         public void RaiseCanExecuteChanged()
  30         {
  31             if (CanExecuteChanged != null)
  32             {
  33                 CanExecuteChanged(this, EventArgs.Empty);
  34             }
  35         }
  36     }
  37 
  38 }

ProgrammingLinks/ICommand (last edited 2019-03-07 15:30:29 by scot)