comparison MetroWpf/MetroWpf.Framework/Extensions/PropertyExtensions.cs @ 15:060f02cd4591

Initial commit, pre airport work
author stevenh7776 stevenhollidge@hotmail.com
date Mon, 12 Mar 2012 23:05:21 +0800
parents
children
comparison
equal deleted inserted replaced
14:741981715d94 15:060f02cd4591
1 using System;
2 using System.ComponentModel;
3 using System.Linq.Expressions;
4
5 namespace Chronos.Presentation.ViewModel
6 {
7 /// <summary>
8 /// Property Extension Methods
9 /// </summary>
10 /// <remarks>
11 /// http://reyntjes.blogspot.com/2009/04/master-detail-viewmodel_24.html
12 /// http://blogs.ugidotnet.org/bmatte/archive/2008/11/28/pattern-model-view-viewmodel-inotifypropertychanged-static-reflection-e-extension-methods.aspx
13 /// </remarks>
14 public static class PropertyExtensions
15 {
16 #region · Extension Methods ·
17
18 /// <summary>
19 /// Creates a <see cref="PropertyChangedEventArgs" /> instance for a given property.
20 /// </summary>
21 /// <typeparam name="T"></typeparam>
22 /// <param name="property">The property.</param>
23 /// <returns></returns>
24 public static PropertyChangedEventArgs CreateChangeEventArgs<T>(this Expression<Func<T>> property)
25 {
26 var expression = property.Body as MemberExpression;
27 var member = expression.Member;
28
29 return new PropertyChangedEventArgs(member.Name);
30 }
31
32 /// <summary>
33 /// Returns property name from expression
34 /// </summary>
35 /// <typeparam name="T"></typeparam>
36 /// <param name="property"></param>
37 /// <returns></returns>
38 public static string GetPropertyName<T>(this Expression<Func<T>> property)
39 {
40 var expression = property.Body as MemberExpression;
41
42 return expression.Member.Name;
43 }
44
45 /// <summary>
46 /// Return property name from expression.
47 /// </summary>
48 /// <example>
49 /// <![CDATA[
50 /// Expression<Func<Item, object>> expression = i => i.Name;
51 /// var propertyName = expression.GetPropertyName(); // propertyName = "Name"
52 /// ]]>
53 /// </example>
54 /// <typeparam name="T"></typeparam>
55 /// <typeparam name="TValue"></typeparam>
56 /// <param name="expression"></param>
57 /// <returns></returns>
58 public static string GetPropertyName<T, TValue>(this Expression<Func<T, TValue>> expression)
59 {
60 var lambda = expression as LambdaExpression;
61
62 MemberExpression memberExpression;
63
64 if (lambda.Body is UnaryExpression)
65 {
66 var unaryExpression = lambda.Body as UnaryExpression;
67 memberExpression = unaryExpression.Operand as MemberExpression;
68 }
69 else
70 {
71 memberExpression = lambda.Body as MemberExpression;
72 }
73
74 if (memberExpression != null)
75 {
76 return memberExpression.Member.Name;
77 }
78
79 return null;
80 }
81
82 #endregion
83 }
84 }