Advertisement
atsukanrock

GroupNameAttribute

Mar 25th, 2013
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. public sealed class GroupNameAttribute : Attribute
  2. {
  3.     public GroupNameAttribute(string groupName)
  4.     {
  5.         Guard.ArgumentNotNull(groupName, "groupName");
  6.  
  7.         this.GroupName = groupName;
  8.     }
  9.  
  10.     public string GroupName { get; private set; }
  11.  
  12.     public static void Apply(INotifyPropertyChanged target)
  13.     {
  14.         Guard.ArgumentNotNull(target, "target");
  15.  
  16.         Func<PropertyInfo, bool> isBool = property =>
  17.         {
  18.             if(property.PropertyType != typeof(bool))
  19.             {
  20.                 throw new ArgumentException(
  21.                     string.Format("GroupNameAttribute can be applied only to {0}.", typeof(bool).FullName));
  22.             }
  23.             return true;
  24.         };
  25.         var groups = (from property in target.GetType().GetProperties()
  26.                       from attribute in (GroupNameAttribute[])GetCustomAttributes(property, typeof(GroupNameAttribute))
  27.                       where isBool(property)
  28.                       select new { property, attribute.GroupName }).GroupBy(el => el.GroupName);
  29.  
  30.         foreach(var group in groups)
  31.         {
  32.             var properties = group.Select(g => g.property).ToArray();
  33.             foreach(var property in properties)
  34.             {
  35.                 var currentProperty = property;
  36.                 target.PropertyChanged += (sender, e) =>
  37.                 {
  38.                     if(e.PropertyName != currentProperty.Name) return;
  39.  
  40.                     var newValue = (bool)currentProperty.GetValue(target, null);
  41.                     if(!newValue) return;
  42.  
  43.                     foreach(var otherProperty in properties)
  44.                     {
  45.                         if(otherProperty == currentProperty) continue;
  46.  
  47.                         otherProperty.SetValue(target, false, null);
  48.                     }
  49.                 };
  50.             }
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement