Using collection properties in custom controls


For my demo on an overview of XNA I wanted to build a menu game component which a developer could design at design-time. I wanted to expose a collection of menu items in the Property Window of Visual Studio when the user added my game component to his game (very briefly you can think of game components as custom control). So very simply, I created a property in my custom control and made sure that my strongly typed class was marked as Serializable.

private List<MenuItem> menuitems = new List<MenuItem>();

public List<MenuItem> MenuItems
{
   get { return menuitems; }
   set { menuitems = value; }
}
…
[Serializable]
public class MenuItem
{
   private string name = string.Empty;

   public string Name
   {
      get { return name; }
      set { name = value; }
   }
}

This gives ellipses (the … button) next to your property in the Property Window and clicking on it will open the Collection Editor with a Property Window of my strongly typed class. Unfortunately, after adding some menu items, closing the designer and re-opening it I would get an error that the collection in my resources could not be set to the collection in my custom control and you can’t work on the form.

After some more investigation I found the correct method is to add [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] as an attribute to your property instead of marking the item class as Serializable.

From the MSDN Library “With the DesignerSerializationVisibilityAttribute, you can indicate whether the value for a property is Visible, and should be persisted in initialization code, Hidden, and should not be persisted in initialization code, or consists of Content, which should have initialization code generated for each public, not hidden property of the object assigned to the property.”.

private List<MenuItem> menuitems = new List<MenuItem>();

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<MenuItem> MenuItems
{
   get { return menuitems; }
   set { menuitems = value; }
}

What this means is that Visual Studio will serialize every object in my collection instead of serializing the collection itself.

While I think this attribute is well documented, it was not easy to find and I only chanced upon it after reading reams on how to build custom UI designers. I hope someone finds this post useful.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!