Static reflection INotifyPropertyChanged

Every MVVM framework contains a ViewModelBase with an implementation of INotifyPropertyChanged. Mine's no different, but I wanted to have the flexibility to control when propertychanges are fired, and whether to do other stuff/fire other propertychanges at the same time, all strongly typed (for resharper renaming, navigation etc). Static reflection came into play, and I came up with a solution that gave me the ability to do this:

if ( SetProperty( ref this._company, value, () => this.Company ) )
{
	// update something else, fire other property changes etc ... 
	this.FirePropertyChanged( () => this.Salary );
}

To achieve this I used static reflection as thus

public bool SetProperty<T>( ref T field, T value, Expression<Func<T>> property )
{
	if ( ( Equals( field, default( T ) ) && Equals( value, default( T ) ) )
		  || ( !Equals( field, default( T ) ) && field.Equals( value ) ) )
	{
		return false;
	}
	field = value;
	if ( property != null )
	{
		this.FirePropertyChanged( property );
	}
	return true;
}

public void FirePropertyChanged<T>( Expression<Func<T>> property )
{
	if ( this.PropertyChanged != null )
	{
		this.PropertyChanged( this, new PropertyChangedEventArgs( property.GetPropertyName() ) );
	}
}

public static class StaticReflectionExtensions
{
	public static string GetPropertyName<T>( this Expression<Func<T>> property )
	{
		return ( ( (MemberExpression)property.Body ).Member ).Name;
	}
}
blog comments powered by Disqus