I'm in love with this class:
[Serializable] public class PropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual bool SetProperty<T>(T value, ref T field, Expression<Func<object>> property) { return SetProperty(value, ref field, GetPropertyName(property)); } protected virtual bool SetProperty<T>(T value, ref T field, [CallerMemberName] string propertyName = null) { if (field == null || !field.Equals(value)) { field = value; OnPropertyChanged(propertyName); return true; } return false; } public void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void OnPropertyChanged(Expression<Func<object>> property) { OnPropertyChanged(GetPropertyName(property)); } protected string GetPropertyName(Expression<Func<object>> property) { var lambda = property as LambdaExpression; MemberExpression memberExpression; var unaryExpression = lambda.Body as UnaryExpression; if (unaryExpression != null) { memberExpression = unaryExpression.Operand as MemberExpression; } else { memberExpression = (MemberExpression) lambda.Body; } var propertyInfo = memberExpression?.Member as PropertyInfo; return propertyInfo?.Name ?? string.Empty; } }
A huge advantage of this is that it checks if the value changed. This will minimize the update calls to the view. For your example, it can look like that:
public class Ethernet : PropertyChangedBase { private string _timeStamp; public string TimeStamp { get { return _timeStamp; } set { SetProperty(value, ref _timeStamp); } } }
If you want it really comfortable, you can write a code snippet for that. This would be the snippet part:
<Snippet> <Declarations> <Literal> <ID>PropertyName</ID> <Type>String</Type> <ToolTip>The property name</ToolTip> <Default>NewProperty</Default> </Literal> <Literal> <ID>PropertyType</ID> <Type> </Type> <ToolTip>Replace with the type of the property</ToolTip> <Default>string</Default> </Literal> <Object> <ID>PrivateVariable</ID> <Type>Object</Type> <ToolTip>The name of the private variable</ToolTip> <Default>newPropertyValue</Default> </Object> </Declarations> <Code Language="csharp" Kind="method decl"><![CDATA[ private $PropertyType$ _$PrivateVariable$; public $PropertyType$ $PropertyName$ { get { return _$PrivateVariable$; } set { SetProperty(value, ref _$PrivateVariable$); } }]]></Code> </Snippet>