/ src / settings-ui / Settings.UI / Helpers / RelayCommand.cs
RelayCommand.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using System;
 6  using System.Windows.Input;
 7  
 8  namespace Microsoft.PowerToys.Settings.UI.Helpers
 9  {
10      public partial class RelayCommand : ICommand
11      {
12          private readonly Action _execute;
13          private readonly Func<bool> _canExecute;
14  
15          public event EventHandler CanExecuteChanged;
16  
17          public RelayCommand(Action execute)
18              : this(execute, null)
19          {
20          }
21  
22          public RelayCommand(Action execute, Func<bool> canExecute)
23          {
24              _execute = execute ?? throw new ArgumentNullException(nameof(execute));
25              _canExecute = canExecute;
26          }
27  
28          public bool CanExecute(object parameter) => _canExecute == null || _canExecute();
29  
30          public void Execute(object parameter) => _execute();
31  
32          public void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
33      }
34  
35      [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "abstract T and abstract")]
36      public partial class RelayCommand<T> : ICommand
37      {
38          private readonly Action<T> execute;
39  
40          private readonly Func<T, bool> canExecute;
41  
42          public event EventHandler CanExecuteChanged;
43  
44          public RelayCommand(Action<T> execute)
45              : this(execute, null)
46          {
47          }
48  
49          public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
50          {
51              this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
52              this.canExecute = canExecute;
53          }
54  
55          public bool CanExecute(object parameter) => canExecute == null || canExecute((T)parameter);
56  
57          public void Execute(object parameter) => execute((T)parameter);
58  
59          public void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
60      }
61  }