Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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