First of all and as mentioned already, use a snippet to create the code for you.
Then there are a couple of libraries that can help you with it, or AOP.
And here's something I've been using for a while in applications where raw ui performance on simple controls is irrelevant: a helper class with a Dictionary<string,object>
to hold the actual property backends, and methods to get/set properties of any type, taking an expression as argument in order to avoid using string literals. When using this, a property comes down to
public int SomeProperty
{
get { return properties.Get( model => model.SomeProperty ); }
set { properties.Set( model => model.SomeProperty, value ); }
}
also that Set
call returns true when the value really changed as that is often useful.
Here's some code, with the usual 'use at own risk' etc warning. You just need a NotifyPropertyChangedHelper implementation but that can be found easily (search the net for 'propertychanged helper' for instance, pretty sure it was posted on SO as well)
public class NotifyPropertyChangedMap<T> where T : INotifyPropertyChanged
{
#region Fields
private readonly T propertyContainer;
private readonly Dictionary<string, object> properties;
#endregion
#region Constructors
public NotifyPropertyChangedMap( T propertyContainer )
{
Contract.Requires<ArgumentNullException>( propertyContainer != null, "propertyContainer" );
this.propertyContainer = propertyContainer;
this.properties = new Dictionary<string, object>();
}
#endregion
#region Get and Set
public Property Get<Property>( Expression<Func<T, Property>> expression )
{
var propName = NotifyPropertyChangedHelper.GetPropertyName( expression );
if( !properties.ContainsKey( propName ) )
properties.Add( propName, GetDefault<Property>() );
return (Property) properties[ propName ];
}
public bool Set<Property>( Expression<Func<T, Property>> expression, Property newValue )
{
var propName = NotifyPropertyChangedHelper.GetPropertyName( expression );
if( !properties.ContainsKey( propName ) )
{
properties.Add( propName, newValue );
propertyContainer.RaisePropertyChangedEvent( propName );
}
else
{
if( EqualityComparer<Property>.Default.Equals( (Property) properties[ propName ], newValue ) )
return false;
properties[ propName ] = newValue;
propertyContainer.RaisePropertyChangedEvent( propName );
}
return true;
}
#endregion
#region Implementation
private static Property GetDefault<Property>()
{
var type = typeof( Property );
return (Property) ( type.IsValueType ? Activator.CreateInstance( type ) : null );
}
#endregion
}