Created
November 23, 2015 10:28
-
-
Save makomweb/fe3f1d65e26c7cab7e7c to your computer and use it in GitHub Desktop.
Updated ViewModelBase
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
namespace Sandbox | |
{ | |
public class ExampleViewModel : ViewModelBase | |
{ | |
public string Title | |
{ | |
get { return GetValue(() => Title); } | |
set { SetValue(() => Title, value); } | |
} | |
} | |
public abstract class ViewModelBase : INotifyPropertyChanged | |
{ | |
private readonly Dictionary<string, object> _propertyValueStorage = new Dictionary<string, object>(); | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected T GetValue<T>(Expression<Func<T>> property) | |
{ | |
var expression = property as LambdaExpression; | |
if (expression == null) | |
{ | |
throw new ArgumentException("The property is not a valid lambda expression!", nameof(property)); | |
} | |
var propertyName = ExtractPropertyName(expression); | |
return GetValue<T>(propertyName); | |
} | |
private T GetValue<T>(string propertyName) | |
{ | |
object value; | |
if (_propertyValueStorage.TryGetValue(propertyName, out value)) | |
{ | |
return (T)value; | |
} | |
return default(T); | |
} | |
protected void SetValue<T>(Expression<Func<T>> property, T value) | |
{ | |
var expression = property as LambdaExpression; | |
if (expression == null) | |
{ | |
throw new ArgumentException("The property is not a valid lambda expression!", nameof(property)); | |
} | |
var propertyName = ExtractPropertyName(expression); | |
var currentValue = GetValue<T>(propertyName); | |
if (Equals(currentValue, value)) | |
return; | |
_propertyValueStorage[propertyName] = value; | |
if (PropertyChanged != null) | |
{ | |
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
protected void RaisePropertyChanged(Expression<Func<object>> expression) | |
{ | |
if (PropertyChanged == null) | |
return; | |
var body = expression.Body as MemberExpression; | |
if (body == null && expression.Body is UnaryExpression) | |
{ | |
var unaryExpression = expression.Body as UnaryExpression; | |
body = unaryExpression.Operand as MemberExpression; | |
} | |
PropertyChanged(this, new PropertyChangedEventArgs(body.Member.Name)); | |
} | |
private static string ExtractPropertyName(LambdaExpression expression) | |
{ | |
MemberExpression memberExpression; | |
if (expression.Body is UnaryExpression) | |
{ | |
var unaryExpression = expression.Body as UnaryExpression; | |
memberExpression = unaryExpression.Operand as MemberExpression; | |
} | |
else | |
{ | |
memberExpression = expression.Body as MemberExpression; | |
} | |
return memberExpression.Member.Name; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment