首先,如已提到的,使用片段来为您创建代码。
然后有一些库可以帮助您,或使用AOP。
以下是我在应用程序中使用了一段时间的内容,其中简单控件的原始UI性能无关紧要:带有
Dictionary<string,object>
的辅助类用于保存实际属性后端,以及获取/设置任何类型属性的方法,采用表达式作为参数,以避免使用字符串字面值。 当使用此功能时,属性可转换为
public int SomeProperty
{
get { return properties.Get( model => model.SomeProperty ); }
set { properties.Set( model => model.SomeProperty, value ); }
}
此外,当值真正更改时,Set
调用返回 true,因为这通常很有用。
这里是一些代码,带有通常的“自行承担风险”等警告。您只需要一个NotifyPropertyChangedHelper实现,但可以很容易地找到它(例如,在网络上搜索“propertychanged helper”,我很确定它也发布在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
}
this.
- 根据 ReSharper,这是多余的。小改进 #2:使用基于表达式的强类型NotifyPropertyChange()
并避免魔术字符串。 - Federico Berasategui