Skip to content

Instantly share code, notes, and snippets.

@Krumelur
Created October 18, 2013 14:50
Show Gist options
  • Save Krumelur/7042686 to your computer and use it in GitHub Desktop.
Save Krumelur/7042686 to your computer and use it in GitHub Desktop.
Smart INotifyPropertyChanged version. This allows you to do: public string SomeProperty { get { return base.GetProperty<string> (); } private set { base.SetProperty<string> (value); } } No need to fire anything manually. Name will be determined using CallerMemberNameAttribute.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Xplat_Core
{
public class PropertyChangedBase : INotifyPropertyChanged
{
private Dictionary<string, object> properties = new Dictionary<string, object> ();
/// <summary>
/// Gets the value of a property
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
protected T GetProperty<T> ([CallerMemberName] string name = null)
{
object value = null;
if (this.properties.TryGetValue (name, out value))
{
return value == null ? default(T) : (T)value;
}
return default(T);
}
/// <summary>
/// Sets the value of a property
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="name"></param>
protected void SetProperty<T> (T value, [CallerMemberName] string name = null)
{
if (Equals (value, this.GetProperty<T> (name)))
{
return;
}
this.properties [name] = value;
OnPropertyChanged (name);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged ([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler (this, new PropertyChangedEventArgs (propertyName));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment