Skip to content

Instantly share code, notes, and snippets.

@BrunoVT1992
Last active April 26, 2016 07:40
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 BrunoVT1992/008b84e132e7e9deb50e20647800770c to your computer and use it in GitHub Desktop.
Save BrunoVT1992/008b84e132e7e9deb50e20647800770c to your computer and use it in GitHub Desktop.
Mvvm ICommand implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Mvvm
{
public class Command : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public Command(Action execute)
: this(execute, null)
{
}
public Command(Action execute, Func<bool> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(object parameter)
{
_execute();
}
}
public class Command<T> : ICommand
{
private readonly Action<T> _execute;
private readonly Func<bool> _canExecute;
public Command(Action<T> execute)
: this(execute, null)
{
}
public Command(Action<T> execute, Func<bool> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment