Last active
December 14, 2015 16:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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