Skip to content

Instantly share code, notes, and snippets.

@pshomov
Last active August 29, 2015 14:21
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 pshomov/4e2b51ef94ca3c6cc508 to your computer and use it in GitHub Desktop.
Save pshomov/4e2b51ef94ca3c6cc508 to your computer and use it in GitHub Desktop.
using System;
using Xamarin.Forms;
using System.Linq.Expressions;
using System.ComponentModel;
using System.Reflection;
namespace MVVMEasy
{
class MVVMCommand : Command {
public MVVMCommand (Action<Object> action, Expression<Func<Object, bool>> propExpression)
: base(action, propExpression.Compile())
{
var member = propExpression.Body as MemberExpression;
var expression = member.Expression as ConstantExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' should be a property.",
propExpression.ToString()));
if (expression == null)
throw new ArgumentException(string.Format(
"Expression '{0}' should be a constant expression",
propExpression.ToString()));
var viewModel = (INotifyPropertyChanged)expression.Value;
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propExpression.ToString()));
var propertyName = propInfo.Name;
viewModel.PropertyChanged += (sender, e) => {
if (e.PropertyName == propertyName) {
this.ChangeCanExecute();
};
};
}
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment