Skip to content

Instantly share code, notes, and snippets.

@stakx
Last active August 29, 2015 14:17
Show Gist options
  • Save stakx/646cf001a60d15cf8b1e to your computer and use it in GitHub Desktop.
Save stakx/646cf001a60d15cf8b1e to your computer and use it in GitHub Desktop.
[CallerMemberName]-based implementation of INotifyPropertyChanged
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected ObservableObject()
{
this.properties = new Dictionary<string, object>();
}
protected object GetValue<T>([CallerMemberName] string propertyName = null)
{
return GetProperty(default(T), propertyName);
}
protected object GetProperty<T>(T orDefault, [CallerMemberName] string propertyName = null)
{
object value;
return properties.TryGetValue(propertyName, out value) ? (T)value : orDefault;
}
protected void SetProperty(object value, [CallerMemberName] string propertyName = null)
{
object oldValue;
bool changed = !(properties.TryGetValue(propertyName, out oldValue) && object.Equals(value, oldValue));
properties[propertyName] = value;
if (changed)
{
RaisePropertyChanged(propertyName);
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
private readonly Dictionary<string, object> properties;
}
namespace Example
{
public sealed class ExampleViewModel : ObservableObject
{
public string UserName
{
get { return GetProperty<string>(); }
set { SetProperty(value); }
}
public int Reputation
{
get { return GetProperty<int>(orDefault: 1); }
set { SetProperty(value); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment