PowerToys/src/settings-ui/Settings.UI/Helpers/RelayCommand.cs

62 lines
2.0 KiB
C#
Raw Normal View History

// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
2020-03-12 01:43:32 +08:00
using System.Windows.Input;
namespace Microsoft.PowerToys.Settings.UI.Helpers
{
public class RelayCommand : ICommand
{
private readonly Action _execute;
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)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
2020-03-12 01:43:32 +08:00
}
public bool CanExecute(object parameter) => _canExecute == null || _canExecute();
2020-03-12 01:43:32 +08:00
public void Execute(object parameter) => _execute();
2020-03-12 01:43:32 +08:00
public void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
2020-03-12 01:43:32 +08:00
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "abstract T and abstract")]
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) => canExecute == null || canExecute((T)parameter);
2020-03-12 01:43:32 +08:00
public void Execute(object parameter) => execute((T)parameter);
2020-03-12 01:43:32 +08:00
public void OnCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
2020-03-12 01:43:32 +08:00
}
}