Skip to content

Instantly share code, notes, and snippets.

@davidblurton
Last active December 14, 2015 16:29
Show Gist options
  • Save davidblurton/5115878 to your computer and use it in GitHub Desktop.
Save davidblurton/5115878 to your computer and use it in GitHub Desktop.
ViewModel is a base class for all view models. It handles INotifyPropertyChanged using the C#5 caller member name attribute
public abstract class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected void RaisePropertyChanged([CallerMemberName] string propertyName = string.Empty)
{
if (propertyName = string.Empty)
{
throw new NotSupportedException("Cannot raise property changed on an empty property name. Make sure you are using the C# 5 compiler to make CallerMemberName work.")
}
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
{
var changed = !EqualityComparer<T>.Default.Equals(field, value);
if (changed)
{
field = value;
RaisePropertyChanged(propertyName);
}
return changed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment