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 as a 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<T> : ICommand
   7     {
   8         private readonly Predicate<T> _canExecute;
   9         private readonly Action<T> _execute;
  10 
  11         public event EventHandler CanExecuteChanged;
  12 
  13         public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
  14         {
  15             _execute = execute;
  16             _canExecute = canExecute;
  17         }
  18 
  19         public bool CanExecute(object parameter)
  20         {
  21             return _canExecute == null || _canExecute((T)parameter);
  22         }
  23 
  24         public void Execute(object parameter)
  25         {
  26             _execute((T)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 2022-09-12 18:10:47 by scot)