public static void ValidateAccessors <TProperty>(GetterFunc <TProperty> getter, SetterFunc <TProperty> setter) { if (getter == null) { throw new Exception("Attached Properties must have a getter!"); } if (setter == null) { throw new Exception("Attached Properties must have a setter!"); } string getterName = getter.GetMethodInfo().Name; string setterName = setter.GetMethodInfo().Name; if (!getterName.StartsWith("Get")) { throw new Exception("Getter Error: Attached properties require a getter formatted Get{name}."); } if (!setterName.StartsWith("Set")) { throw new Exception("Setter Error: Attached properties require a setter formatted Set{name}."); } if (getterName.Substring(3) != setterName.Substring(3)) { throw new Exception("Attached properties require a getter and setter formatted Get{name}/Set{name} where the names match."); } }
/// <summary> /// Registers an attached property with the dependency property system. /// </summary> /// <typeparam name="TProperty">The type of the attached property (inferred)</typeparam> /// <param name="ownerType">The attached property owner -- can't be inferred :'(</param> /// <param name="getter">The attached property's getter (verified for required verbiage and type).</param> /// <param name="setter">The attached property's setter (verified for required verbiage and type).</param> /// <param name="metadata">The property metadata to register for this attached property with the dependency property system.</param> /// <returns>The <see cref="DependencyProperty"/> that was registered for this attached property.</returns> /// <exception cref="System.Exception"> /// APUtils::Register - Getter Error - Attached properties require a getter formatted Get{name}. /// or /// APUtils::Register - Setter Error - Attached properties require a getter formatted Set{name}. /// or /// APUtils::Register - Attached properties require a getter and setter formatted Get{name}/Set{name} where the names match. /// </exception> public static DependencyProperty Register <TProperty>(Type ownerType, GetterFunc <TProperty> getter, SetterFunc <TProperty> setter, PropertyMetadata metadata) { ValidateAccessors(getter, setter); // Could use getter or setter, it's the same either way string name = getter.GetMethodInfo().Name.Substring(3); return(DependencyProperty.RegisterAttached(name, typeof(TProperty), ownerType, metadata)); }