Strongly typing INotifyPropertyChanged
August 26, 2011 Leave a comment
The following implementation is a slight modification to Paul Stovell’s strongly-typed names for INotifyPropertyChanged found on his blog http://www.paulstovell.com/strong-property-names
I have taken Paul’s idea and extended it slightly.
First I have declared a static class for Property.
public class Property
{
public static string Name(Expression<Func<object>> propertyNameLambda)
{
MemberExpression member = propertyNameLambda.Body as MemberExpression;
if (member == null)
{
var unaryExpression = (propertyNameLambda.Body as UnaryExpression);
member = unaryExpression.Operand as MemberExpression;
}
return member.Member.Name;
}
}
I have then declared an ObservableObject class that has the following implementation:
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void NotifyPropertyChanged(params string[] propertyNames)
{
foreach (var propertyName in propertyNames)
{
NotifyPropertyChanged(propertyName);
}
}
protected void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void NotifyPropertyChanged(params Expression<Func<object>>[] propertyExpressions)
{
foreach (var propertyExpression in propertyExpressions)
{
NotifyPropertyChanged(propertyExpression);
}
}
protected void NotifyPropertyChanged(Expression<Func<object>> propertyNameLambda)
{
this.NotifyPropertyChanged(Property.Name(propertyNameLambda));
}
}
This class enables us to either use lamba expressions or string to raise that the property has changed. Interestingly enough we can now pass in as many expressions as we like on the method call as we have overloaded the method to use params.
eg
NotifyPropertyChanged(() => TestResultDetails, () => CollectionView, () => IsPassedSelected);
Where TestResultDetails, CollectionView, IsPassedSelected are all properties inside the view model.
Better yet we can now use the Property.Name method inside the event handler.
eg
void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == Property.Name(() => IsPassedSelected))
{
// Do stuff
}
}
