Skip to content

Instantly share code, notes, and snippets.

@btshft
Last active June 5, 2016 21:32
Show Gist options
  • Save btshft/277936367a3cdd1be00e4b843cda5128 to your computer and use it in GitHub Desktop.
Save btshft/277936367a3cdd1be00e4b843cda5128 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