Created
March 23, 2016 16:19
-
-
Save arijusg/32880f176b4985adc94a to your computer and use it in GitHub Desktop.
ChangeAndNotify WPF extention
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 static class ChangeAndNotifyExtention | |
{ | |
public static bool ChangeAndNotify<T>(this PropertyChangedEventHandler handler, | |
ref T field, T value, Expression<Func<T>> memberExpression) | |
{ | |
if (memberExpression == null) | |
{ | |
throw new ArgumentNullException("memberExpression"); | |
} | |
var body = memberExpression.Body as MemberExpression; | |
if (body == null) | |
{ | |
throw new ArgumentException("Lambda must return a property."); | |
} | |
if (EqualityComparer<T>.Default.Equals(field, value)) | |
{ | |
return false; | |
} | |
field = value; | |
var vmExpression = body.Expression as ConstantExpression; | |
if (vmExpression != null) | |
{ | |
LambdaExpression lambda = Expression.Lambda(vmExpression); | |
Delegate vmFunc = lambda.Compile(); | |
object sender = vmFunc.DynamicInvoke(); | |
if (handler != null) | |
{ | |
handler(sender, new PropertyChangedEventArgs(body.Member.Name)); | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment