Skip to content

Instantly share code, notes, and snippets.

@flq
Created February 18, 2011 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flq/833551 to your computer and use it in GitHub Desktop.
Save flq/833551 to your computer and use it in GitHub Desktop.
A command that runs on delegates and implements WPF ICommand
using System;
using System.Windows.Input;
namespace Something
{
public class RelayCommand : ICommand
{
private readonly Func<object, bool> _canExecute;
private readonly Action<object> _execute;
public RelayCommand(Func<object, bool> canExecute, Action<object> execute)
{
_canExecute = canExecute;
_execute = execute;
}
public RelayCommand(Action<object> execute) : this(_ => true, execute) { }
public RelayCommand(Action execute) : this(_ => true, _ => execute()) { }
public RelayCommand(Func<bool> canExecute, Action execute) : this(_ => canExecute(), _ => execute()) { }
public void Execute(object parameter)
{
_execute(parameter);
}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment