Skip to content

Instantly share code, notes, and snippets.

@hassanselim0
Last active August 29, 2015 14:06
Show Gist options
  • Save hassanselim0/494e215363465d4a7a10 to your computer and use it in GitHub Desktop.
Save hassanselim0/494e215363465d4a7a10 to your computer and use it in GitHub Desktop.
INotifyPropertyChanged Idea
using System.ComponentModel;
using System.Runtime.CompilerServices;
public abstract class NotifyPropChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Because of "ref", reassigning the value will work, for both value types and reference types!
// And thanks to CallerMemberName (.Net 4.5), the compiler will fill in the member name for you :)
protected void UpdateValue<T>(ref T currVal, T newVal, [CallerMemberName] string propName = "")
{
if (EqualityComparer<T>.Default.Equals(currVal, newVal)) return;
currVal = newVal;
CallPropChanged(propName);
}
// This is here in case you might need to explicitly call PropertyChanged
// You can even bypass the CallerMemberName trick by passing your own string
protected void CallPropChanged([CallerMemberName] string propName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public class MyViewModel : NotifyPropChanged
{
private int someInt;
public int SomeInt
{
get { return someInt; }
set { UpdateValue(ref someInt, value); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment