Advertisement
Guest User

Untitled

a guest
Nov 30th, 2014
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. // this class implements the functionality of Prism's CompositeCommand
  2. public class CompositeCommand : ICommand
  3. {
  4.     List<ICommand> innerCommands = new List<ICommand>();
  5.  
  6.     public CompositeCommand() : this(_ => true)
  7.     {
  8.     }
  9.  
  10.     public CompositeCommand(Func<ICommand, bool> shouldExecute)
  11.     {
  12.         this.shouldExecute = shouldExecute;
  13.     }
  14.  
  15.     public void RegisterCommand(ICommand command)
  16.     {
  17.         innerCommands.Add(command);
  18.         command.CanExecuteChanged += OnCanExecuteChanged;
  19.     }
  20.  
  21.     public void UnregisterCommand(ICommand command)
  22.     {
  23.         command.CanExecuteChanged -= OnCanExecuteChanged;
  24.         innerCommands.Remove(command);
  25.     }
  26.  
  27.     private void OnCanExecuteChanged(object sender, EventArgs args)
  28.     {
  29.         OnCanExecuteChanged();
  30.     }
  31.  
  32.     protected virtual void OnCanExecuteChanged()
  33.     {
  34.         var copy = CanExecuteChanged;
  35.         if (copy != null)
  36.             copy(this, new EventArgs());
  37.     }
  38.  
  39.     public bool CanExecute(object parameter)
  40.     {
  41.         return innerCommands.Where(ShouldExecute).Select(c => c.CanExecute(parameter)).AllTrue();
  42.     }
  43.  
  44.     public event EventHandler CanExecuteChanged;
  45.  
  46.     public void Execute(object parameter)
  47.     {
  48.         var commandsToExecute = innerCommands.Where(ShouldExecute).Materialize();
  49.         foreach (var command in commandsToExecute)
  50.             command.Execute(parameter);
  51.     }
  52.  
  53.     Func<ICommand, bool> shouldExecute;
  54.  
  55.     protected virtual bool ShouldExecute(ICommand command)
  56.     {
  57.         return shouldExecute(command);
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement