Last active
August 29, 2015 14:06
-
-
Save hassanselim0/494e215363465d4a7a10 to your computer and use it in GitHub Desktop.
INotifyPropertyChanged Idea
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
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