First of all, as already mentioned, use the code snippet to create the code for you. Then there are several libraries that can help you, or AOP.
And here is something that I used for some time in applications where raw ui performance on simple controls does not matter: a helper class with Dictionary<string,object> for storing actual internal resources and methods for getting / setting properties of any type, accepting an expression as an argument to avoid using string literals. When using this property, the property is reduced to
public int SomeProperty { get { return properties.Get( model => model.SomeProperty ); } set { properties.Set( model => model.SomeProperty, value ); } }
also that calling Set returns true when the value really changes, as this is often useful.
Here is some code, with the usual warning about "using at your own risk." You just need an implementation of NotifyPropertyChangedHelper, but it can be easily found (for example, a network search for the “propertychanged helper”, it’s pretty sure that it was also hosted on SO)
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 }
stijn source share