Skip to content

Instantly share code, notes, and snippets.

@kucheruk
Created May 7, 2015 11:48
Show Gist options
  • Save kucheruk/dfd7b443ec6fd68f58f1 to your computer and use it in GitHub Desktop.
Save kucheruk/dfd7b443ec6fd68f58f1 to your computer and use it in GitHub Desktop.
Subscrible Viewmodel
public abstract class BaseObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Setter<T>(ref T setter, T newVal, Expression<Func<T>> property, params Expression<Func<object>>[] dependentProperties)
{
if (!equals(GetPropValue(property), newVal))
{
setter = newVal;
NotifyDependentProps(property, dependentProperties);
}
}
private static string GetPropertyName<TZ>(Expression<Func<TZ>> property)
{
return GetPropertyInfo(property).Name;
}
private static PropertyInfo GetPropertyInfo<T>(Expression<Func<T>> property)
{
MemberExpression expression;
var body = property.Body as UnaryExpression;
if (body != null)
expression = (MemberExpression)body.Operand; //for value types
else
expression = ((MemberExpression)property.Body);
var pi = expression.Member as PropertyInfo;
if (pi == null)
throw new ArgumentException("expression must be valid property");
return pi;
}
private void ValueChanged<TA>(Expression<Func<TA>> property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(GetPropertyName(property)));
}
private void NotifyDependentProps<T>(Expression<Func<T>> property, Expression<Func<object>>[] dependentProps)
{
ValueChanged(property);
if (dependentProps != null && dependentProps.Length > 0)
{
foreach (Expression<Func<object>> t in dependentProps)
ValueChanged(t);
}
}
private T GetPropValue<T>(Expression<Func<T>> property)
{
PropertyInfo pi = GetPropertyInfo(property);
return (T)pi.GetValue(this, new object[] { });
}
private bool equals<T>(T first, T second)
{
return EqualityComparer<T>.Default.Equals(first, second);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment