RelayCommand`1.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.Library.ViewModels.Commands
 9  {
10      public class RelayCommand<T> : ICommand
11      {
12          private readonly Action<T> execute;
13  
14          private readonly Func<T, bool> canExecute;
15  
16          public event EventHandler CanExecuteChanged;
17  
18          public RelayCommand(Action<T> execute)
19              : this(execute, null)
20          {
21          }
22  
23          public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
24          {
25              this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
26              this.canExecute = canExecute;
27          }
28  
29          public bool CanExecute(object parameter) => canExecute == null || canExecute((T)parameter);
30  
31          public void Execute(object parameter) => execute((T)parameter);
32  
33          public void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
34      }
35  }