Serialize properties correctly with DesignerSerializationVisibilityAttribute
System.ComponentModel.DesignerSerializationVisibilityAttribute specifies
what part of a property should be serialized by the designer. This attribute is
usually necessary when creating custom Web and Windows controls.
This attribute takes one parameter, which is a System.ComponentModel.DesignerSerializationVisibility
enumeration member:
-
Visible - specifies that the object should be
serialized.
Use this value for simple (or primitive) properties.
-
Content - specifies that contents of the object should be
serialized.
Use this value for complex (or non-primitive) properties and collections.
-
Hidden- specifies that the object should not
be serialized. Use this value when properties are changed for
design-time purposes only, but should not be serialized in code.
Note that DesignerSerializationVisibilityAttribute and
DesignerSerializationVisibility are two different types.
Let's look at an example for clarity.
Example
public class SearchControl
{
private TextBox _searchTextBox = new TextBox();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TextBox SearchTextBox
{
get
{
return _searchTextBox;
}
}
}
The above sample control gets serialized the following way on a Windows Form:
this.MySearchControl = new SearchControl();
this.MySearchControl.SearchTextBox.Length = 1;
this.MySearchControl.SearchTextBox.BackColor = System.Drawing.Color.White;
Because the value Content is used, the properties of
SearchTextBox are serialized.
If the control were a Web Forms control, it would be serialized the following
way:
<asp:SearchControl SearchTextBox-Length="1" SearchTextBox-BackColor="White"></asp:SearchControl>
An even better way to see the use of DesignerSerializationVisibility is to add
the attribute to a string property, try different values, and
examine the result. The following snippet shows a control with two string
properties, one serialized using Content and the other using
Visible:
<asp:MyControl ContentSerializedString-Length="15" VisibleSerializedString="AnEasierSnippet"/>
Back to Tips and Tricks