问题
I have a C# component which has two properties, Property1 and Property2. Property1 is a simple property of type int and Property2 is a List where T is a custom class. Property2 has the DesignerSerializationVisibility.Content attribute set.
When Property1 is set at Designtime the component should generate the number of custom classes that is set. This works but the classes aren't serialized to the Designer.cs file. When I add a custom class through the standard collection editor of Visual Studio the class is serialized to the Designer.cs file.
How can I get Visual Studio to also serialize the generated classes to the Designer.cs file?
Here is a small sample 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; }
}
}
回答1:
The Columns property does not have a setter. The serialiser will ignore 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:
NOTE: answer was provided by @urk_forever within the body of his question. I have rolled the question back to it's original state and copied the changes here as CW
UPDATE: I have found the solution already. I had to add this line:
this.Container.Add(tClass); to get the Designer to serialize the generated classes. I have updated the code below to reflect this change. Now the classes are serialized to the Designer.cs.
Code changed as follows within the 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
}
来源:https://stackoverflow.com/questions/5736034/c-sharp-component-collection-property-not-serialized-when-filled-from-property-s