Inside GenericWebPart - IAttributeAccessor
Within the web part framework there is a powerful feature that allows us to turn ordinary web controls into web parts simply by dropping them onto a zone. The real beauty of this is that we can even treat the web control as a web part in markup. The following snippet of code shows a Label being assigned an ExportMode property value:
<asp:Label id="Label1" runat="server" ExportMode="NonSensitiveData" />
Clearly the Label control has no such property so how is it that this property can be added in markup and inferred to the underlying web part. The secret lies in 2 things: a property on GenericWebPart named ChildControl and the IAttributeAccessor interface.
The ChildControl holds onto the instance of real underlying control. This control, by virtue of the fact that it is a WebControl, implements the IAttributeAccessor interface. This interface has 2 members of interest - GetAttribute and SetAttribute - which allow controls to accept arbitrary attribute values. These are referred to as expando properties. In the example above, the ExportMode value for the Label would have been stored away and retrieved from these expando properties.
When you attempt to set these properties at runtime they will not exist on the underlying controls so the thing to do is to get the actual GenericWebControl instance and set them from there. Here is an example of setting the ExportMode of the Label at runtime:
GenericWebPart gwp =
gwp.ExportMode = WebPartExportMode.NonSensitiveData;
If you need to implement expando properties in your own controls then consider implemeting the IAttributeAccessor interface.