Last active
August 29, 2015 14:12
-
-
Save AndrewJByrne/df6ddd90c9423075fbc7 to your computer and use it in GitHub Desktop.
Shows a simple base class for a ViewModel that implements INotifyPropertyChanged and uses the CallerMemberName attribute to default the name of the property when the PropertyChanged event is raised. Saves some typing and reduces the use of strings coded manually in your ViewModel.
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Diagnostics; | |
using System.Runtime.CompilerServices; | |
using System.Text; | |
namespace My.Gists | |
{ | |
/// <summary> | |
/// Shows how to raise a PropertyChanged notification, using as default the name of the property that | |
/// calls SetProperty. | |
/// For info on the CallerMemberName attribute, see http://msdn.microsoft.com/en-us/library/windows/apps/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx | |
/// </summary> | |
public class ViewModelBase : INotifyPropertyChanged | |
{ | |
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = "") | |
{ | |
// If the value is the same as the current value, return false to indicate this was a no-op. | |
if (Object.Equals(field, value)) | |
return false; | |
// Raise any registered property changed events and indicate to the user that the value was indeed changed. | |
field = value; | |
NotifyPropertyChanged(propertyName); | |
return true; | |
} | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected void NotifyPropertyChanged([CallerMemberName]string propertyName = "") | |
{ | |
if (PropertyChanged != null) | |
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
/// <summary> | |
/// An example use of the ViewModelBase class. | |
/// </summary> | |
public class MyViewModel : ViewModelBase | |
{ | |
int _myProperty = 0; | |
public int MyProperty | |
{ | |
get | |
{ | |
return _myProperty; | |
} | |
set | |
{ | |
if (SetProperty(ref _myProperty, value)) | |
{ | |
Debug.WriteLine("Property has indeed changed"); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment