Skip to content

Instantly share code, notes, and snippets.

@ap0llo
Created October 16, 2016 15:08
Show Gist options
  • Save ap0llo/14b7ba010f76f9e655d5e6b453e54b80 to your computer and use it in GitHub Desktop.
Save ap0llo/14b7ba010f76f9e655d5e6b453e54b80 to your computer and use it in GitHub Desktop.
RelayCommand
using System;
using System.Windows.Input;
namespace Snippet
{
public class RelayCommand : ICommand
{
readonly Action<object> m_Execute;
readonly Func<object, bool> m_CanExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action execute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
m_Execute = _ => execute();
m_CanExecute = null;
}
public RelayCommand(Action<object> execute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
m_Execute = execute;
m_CanExecute = null;
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
if (canExecute == null)
throw new ArgumentNullException(nameof(canExecute));
m_Execute = _ => execute();
m_CanExecute = _ => canExecute();
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
if (canExecute == null)
throw new ArgumentNullException(nameof(canExecute));
m_Execute = execute;
m_CanExecute = canExecute;
}
public bool CanExecute(object parameter) => m_CanExecute?.Invoke(parameter) ?? true;
public void Execute(object parameter) => m_Execute(parameter);
public static Lazy<RelayCommand> Lazy(Action execute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
return new Lazy<RelayCommand>(() => new RelayCommand(execute));
}
public static Lazy<RelayCommand> Lazy(Action<object> execute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
return new Lazy<RelayCommand>(() => new RelayCommand(execute));
}
public static Lazy<RelayCommand> Lazy(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
if (canExecute == null)
throw new ArgumentNullException(nameof(canExecute));
return new Lazy<RelayCommand>(() => new RelayCommand(execute, canExecute));
}
public static Lazy<RelayCommand> Lazy(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
if (canExecute == null)
throw new ArgumentNullException(nameof(canExecute));
return new Lazy<RelayCommand>(() => new RelayCommand(execute, canExecute));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment