Skip to content

Instantly share code, notes, and snippets.

@BrunoVT1992

BrunoVT1992/Command.cs

Last active Apr 26, 2016
Embed
What would you like to do?
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
You can’t perform that action at this time.