1. Contesto

Le RelayCommand e RelayCommand<T> sono implementazioni ICommand che possono esporre un metodo o un delegato alla vista. Questi tipi fungono da modo per associare i comandi tra il modello di visualizzazione e gli elementi dell'interfaccia utente.

2. Implementazione

Si crea una classe specifica PUBBLICA che possa essere utilizzata in tutta l'applicazione

1public class RelayCommand<T> : ICommand2{3 #region Private members4 /// <summary>5 /// Creates a new command that can always execute.6 /// </summary>7 private readonly Action<T> _execute;8 /// <summary>9 /// True if command is executing, false otherwise10 /// </summary>11 readonly Predicate<T> _canExecute = null;12 #endregion13 /// <summary>14 /// Initializes a new instance of <see cref="RelayCommand"/>15 /// </summary>16 /// <param name="execute">The execution logic.</param>17 /// <param name="canExecute">The execution status logic.</param>18 public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)19 {20  if (execute == null)21  {22   throw new ArgumentNullException("execute");23  }24  _execute = execute;25  _canExecute = canExecute;26 }27 /// <summary>28 /// Raised when RaiseCanExecuteChanged is called.29 /// </summary>30 public event EventHandler CanExecuteChanged31 {32  add { CommandManager.RequerySuggested += value; }33  remove { CommandManager.RequerySuggested -= value; }34 }35 #region ICommand Members36 /// <summary>37 /// Determines whether this <see cref="RelayCommand"/> can execute in its current state.38 /// </summary>39 /// <param name="parameter">40 /// Data used by the command. If the command does not require data to be passed, this object can be set to null.41 /// </param>42 /// <returns>True if this command can be executed; otherwise, false.</returns>43 public bool CanExecute(object parameter)44 {45  return (_canExecute == null || _canExecute((T)parameter));46 }47 /// <summary>48 /// Executes the <see cref="RelayCommand"/> on the current command target.49 /// </summary>50 /// <param name="parameter">51 /// Data used by the command. If the command does not require data to be passed, this object can be set to null.52 /// </param>53 public void Execute(object parameter)54 {55  _execute((T)parameter);56 }57 #endregion ICommand Members58}59public class RelayCommand : RelayCommand<object>60{61 public RelayCommand(Action<object> execute)62 : base(execute, null)63 { }64 public RelayCommand(Action<object> execute, Predicate<object> canExecute)65 : base(execute, canExecute)66 { }67}

Nel code-behind delle pagine in cui vogliamo implementare il RelayCommand andremo a definire il comportamento dell'ICommand

1private ICommand _playMatch;2public ICommand PlayMatch3{4 get5 {6  if (_playMatch == null)7   _playMatch = new RelayCommand((p) => PlayMatch_Action());89  return _playMatch;10 }11}

e nel file XAML andiamo ad associare al Button il nostro ICommand

1<Button Command="{Binding PlayMatch, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

3. Risultato

In questo modo quando viene premuto il pulsante dello XAML, viene richiamato RelativeSource PlayMatch che, nel code-behind utilizza la classe RelayCommand che richiama il metodo PlayMatch_Action().