Skip to content

Instantly share code, notes, and snippets.

@mrousavy
Created September 25, 2017 07:56
Show Gist options
  • Save mrousavy/d308d2c4d9e12613eed2871a0ea48bad to your computer and use it in GitHub Desktop.
Save mrousavy/d308d2c4d9e12613eed2871a0ea48bad to your computer and use it in GitHub Desktop.
An event basede ICommand implementation for WPF
using System;
using System.Windows.Input;
public class RelayCommand : ICommand {
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null) {
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute ?? (o => true);
}
public event EventHandler CanExecuteChanged {
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object parameter) {
return _canExecute(parameter);
}
public void Execute(object parameter) {
_execute(parameter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment