Created
January 28, 2014 10:41
-
-
Save lkaczanowski/8665456 to your computer and use it in GitHub Desktop.
INotifyPropertyChanged with property expressions
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
| public class NotifyPropertyBase : INotifyPropertyChanged | |
| { | |
| public event PropertyChangedEventHandler PropertyChanged; | |
| protected virtual void OnPropertyChanged( Expression<Func<object>> propertyExpression ) | |
| { | |
| PropertyChangedEventHandler handler = PropertyChanged; | |
| if (handler != null) handler( this, new PropertyChangedEventArgs( GetPropertyName( propertyExpression ) ) ); | |
| } | |
| private string GetPropertyName( Expression<Func<object>> propertyExpression ) | |
| { | |
| var unaryExpression = propertyExpression.Body as UnaryExpression; | |
| var memberExpression = unaryExpression == null ? (MemberExpression)propertyExpression.Body : (MemberExpression)unaryExpression.Operand; | |
| var propertyName = memberExpression.Member.Name; | |
| return propertyName; | |
| } | |
| } |
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
| private int _myProperty; | |
| public int MyProperty | |
| { | |
| get { return _myProperty; } | |
| set | |
| { | |
| if (_myProperty == value) return; | |
| _myProperty = value; | |
| OnPropertyChanged( ( ) => MyProperty ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment