Skip to content

Instantly share code, notes, and snippets.

@heiswayi
Forked from btshft/Bindable.cs
Created June 5, 2016 21:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save heiswayi/3d28bd407321d169ae6348860f9bf998 to your computer and use it in GitHub Desktop.
Save heiswayi/3d28bd407321d169ae6348860f9bf998 to your computer and use it in GitHub Desktop.
Bindable class to reduce boilerplate code in mvvm (implement INotifyPropertyChanged)
namespace Helpers
{
///<summary>
/// Reduce mvvm boilerplate
///
/// Usage:
/// public class MyViewModel : Bindable {
/// // Now this property supports INotifyPropertyChanged
/// public string MyProperty
/// {
/// get { return Get<string>(); }
/// set { Set(value); }
/// }
/// }
///</summary>
public class Bindable : INotifyPropertyChanged
{
private readonly Dictionary<string, object> _properties
= new Dictionary<string, object>();
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the value of a property
/// </summary>
protected T Get<T>([CallerMemberName] string name = null)
{
object value;
if (_properties.TryGetValue(name, out value))
return value == null ? default(T) : (T) value;
return default(T);
}
/// <summary>
/// Sets the value of a property
/// </summary>
protected void Set<T>(T value, [CallerMemberName] string name = null)
{
if (Equals(value, Get<T>(name)))
return;
_properties[name] = value;
OnPropertyChanged(name);
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment