wpf 4.0 - WPF Attached property not working for setting HorizontalAlignment in child elements -


in our wpf 4.0 projects (not silverlight), using several custom attached properties set property values in children of container, typically grid or stackpanel. prefer strategy on styles , other alternatives can use less of line of code, in same declaration of container.

we have custom attached property setting several typical properties, margin properties of children of container. experiencing problem 1 of them, horizontalalignmentproperty. custom attached property identical others:

public class horizontalalignmentsetter {     public static readonly dependencyproperty horizontalalignmentproperty = dependencyproperty.registerattached("horizontalalignment", typeof(horizontalalignment), typeof(horizontalalignmentsetter), new uipropertymetadata(horizontalalignment.left, horizontalalignmentchanged));     public static horizontalalignment gethorizontalalignment(dependencyobject obj) { return (horizontalalignment)obj.getvalue(horizontalalignmentproperty); }     public static void sethorizontalalignment(dependencyobject obj, horizontalalignment value) { obj.setvalue(horizontalalignmentproperty, value); }      private static void horizontalalignmentchanged(object sender, dependencypropertychangedeventargs e)     {         var panel = sender panel;         if (panel == null) return;         panel.loaded += panelloaded;     }      static void panelloaded(object sender, routedeventargs e)     {         var panel = (panel)sender;         foreach (var child in panel.children)         {             var fe = child frameworkelement;             if (fe == null) continue;             fe.horizontalalignment = gethorizontalalignment(panel);         }     } } 

an usage in xaml identical:

<grid util:horizontalalignmentsetter.horizontalalignment="left">     <label .../>     <textbox .../> </grid> 

the attached property not invoked , property values not set in children of grid. debugging application see the static property declaration (public static readonly dependencyproperty horizontalalignmentproperty = dependencyproperty.registerattached...) invoked no other code invoked, sethorizontalalignment(dependencyobject obj... , callback private static void horizontalalignmentchanged(object sender,....

any ideas?

in xaml you're setting property default value not cause propertychanged handler fire. boilerplate , set methods never called unless call them code because properties set in xaml call getvalue , setvalue directly (as case wrapper properties on normal dp).

to ensure change handler called when value set use nullable<horizontalalignment> instead , set default null.


Comments