Skip to content

Instantly share code, notes, and snippets.

@EfrainReyes
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EfrainReyes/88033d2f3aa3cff000e7 to your computer and use it in GitHub Desktop.
Save EfrainReyes/88033d2f3aa3cff000e7 to your computer and use it in GitHub Desktop.
Using INotifyPropertyChanged without having to pass the property name or an expression. Running Example: https://dotnetfiddle.net/4P0dhM
public class CustomerModel : ModelBase {
private string _customerName;
public string CustomerName {
get { return _customerName; }
set { SetProperty(ref _customerName, value); }
}
private int _orderCount;
public int OrderCount {
get { return _orderCount; }
set { SetProperty(ref _orderCount, value); }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public abstract class ModelBase : INotifyPropertyChanged, IDisposable {
private event PropertyChangedEventHandler _propertyChanged;
private List<PropertyChangedEventHandler> _propertyChangedSubscribers =
new List<PropertyChangedEventHandler>();
// this is Miguel Castro's technique from his Pluralsight course
// where he can add a delegate to an event handler
// without having to worry about duplicates
public event PropertyChangedEventHandler PropertyChanged {
add {
if (!_propertyChangedSubscribers.Contains(value)) {
_propertyChanged += value;
_propertyChangedSubscribers.Add(value);
}
}
remove {
_propertyChanged -= value;
_propertyChangedSubscribers.Remove(value);
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void SetProperty<T>(ref T field, T value, [CallerMemberName]string property = "") {
if (!EqualityComparer<T>.Default.Equals(field, value)) {
field = value;
NotifyPropertyChanged(property);
}
}
// my own little twist
// http://stackoverflow.com/q/1061727/2563028
// this way instead of unregistering event handlers manually
// one can simply Dispose() the object
public void Dispose() {
_propertyChanged = null;
_propertyChangedSubscribers.Clear();
}
}
using System;
public class Program
{
public static void Main()
{
using (var model = new CustomerModel()) {
model.PropertyChanged += (sender, e) => {
Console.WriteLine("{0}: {1}", e.PropertyName, sender.GetType().GetProperty(e.PropertyName).GetValue(sender));
};
model.CustomerName = "Efraín Reyes";
model.OrderCount = 5;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment