Last active
April 26, 2016 07:40
-
-
Save BrunoVT1992/008b84e132e7e9deb50e20647800770c to your computer and use it in GitHub Desktop.
Mvvm ICommand implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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