C # Component collection property not serialized when populated using property setting tool

I have a C # component that has two properties: Property1 and Property2. Property 1 is a simple property of type int, and property2 is a list, where T is a custom class. Property2 has the DesignerSerializationVisibility.Content attribute.

When Property1 is set to Designtime, the component must generate the number of custom user classes. This works, but the classes are not serialized in the Designer.cs file. When I add a custom class through the standard Visual Studio collection editor, the class is serialized in the Designer.cs file.

How can I make Visual Studio also serialize the generated classes in the Designer.cs file?

Here is a small example of what I have now:

public class TestComponent : Component
{
    private int _Count;
    public int Count
    {
        get { return _Count; }
        set 
        { 
            _Count = value;

            Columns.Clear();

            for (int i = 0; i < _Count; i++)
            {
                TestClass tClass = new TestClass();
                tClass.Description = "TestClass" + i.ToString();
                Columns.Add(tClass);
            }
        }
    }

    private List<TestClass> columns = new List<TestClass>();
    [EditorBrowsable(EditorBrowsableState.Never)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public List<TestClass> Columns 
    { 
            get { return columns; } 
    }
}

[ToolboxItem(false), DesignTimeVisible(false)]
public class TestClass : Component
{
    private string _Description;
    public string Description
    {
        get { return _Description; }
        set { _Description = value; }
    }
}
0
source share
2 answers

The Columns property does not have a setter. The serializer ignores this property. Change to this:

private List<TestClass> columns = new List<TestClass>();
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<TestClass> Columns 
{ 
        get { return columns; } 
        set { columns = value; }
}
+2
source

NOTE: the answer was provided by @urk_forever in the body of his question. I returned the question back to its original state and copied the changes here as CW


UPDATE: I found a solution already. I had to add this line:

this.Container.Add (tClass); so that the constructor can serialize the created classes. I updated the code below to reflect this change. Classes are now serialized in Designer.cs.

The code was changed as follows in for-loop[IAbstract]

for (int i = 0; i < _Count; i++)
{
    TestClass tClass = new TestClass();
    tClass.Description = "TestClass" + i.ToString();
    Columns.Add(tClass);
    this.Container.Add(tClass);   // <-- added
}
+1
source

All Articles