PowerToys/src/core/Microsoft.PowerToys.Settings.UI/Helpers/RelayCommand.cs

58 lines
1.7 KiB
C#
Raw Normal View History

2020-03-12 01:43:32 +08:00
using System;
using System.Windows.Input;
namespace Microsoft.PowerToys.Settings.UI.Helpers
{
public class RelayCommand : ICommand
{
private readonly Action execute;
2020-03-12 01:43:32 +08:00
private readonly Func<bool> canExecute;
2020-03-12 01:43:32 +08:00
public event EventHandler CanExecuteChanged;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.canExecute = canExecute;
2020-03-12 01:43:32 +08:00
}
public bool CanExecute(object parameter) => this.canExecute == null || this.canExecute();
2020-03-12 01:43:32 +08:00
public void Execute(object parameter) => this.execute();
2020-03-12 01:43:32 +08:00
public void OnCanExecuteChanged() => this.CanExecuteChanged?.Invoke(this, EventArgs.Empty);
2020-03-12 01:43:32 +08:00
}
public class RelayCommand<T> : ICommand
{
private readonly Action<T> execute;
2020-03-12 01:43:32 +08:00
private readonly Func<T, bool> canExecute;
2020-03-12 01:43:32 +08:00
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
{
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.canExecute = canExecute;
2020-03-12 01:43:32 +08:00
}
public bool CanExecute(object parameter) => this.canExecute == null || this.canExecute((T)parameter);
2020-03-12 01:43:32 +08:00
public void Execute(object parameter) => this.execute((T)parameter);
2020-03-12 01:43:32 +08:00
public void OnCanExecuteChanged() => this.CanExecuteChanged?.Invoke(this, EventArgs.Empty);
2020-03-12 01:43:32 +08:00
}
}