Search code examples
c#propertygrid

How to save readonly property value in PropertyGrid


I have a custom class:

[TypeConverter(typeof(ExpandableObjectConverter))]
public class CustomClass
{
    public int State { get; set; }
}

A readonly property:

public class MyControl : UserControl
{
    public CustomClass MyProperty { get; } = new CustomClass();
}

The property is shown and editable in the properties window.

PropertyGrid

But the value is not saved, if reopen the designer, it's restored.

I think it's not hard for designer to generate code like:

myControl.MyProperty.State = 1;

How to make the readonly property savable?


Solution

  • After several days searching I find a solution, very simple:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public CustomClass MyProperty { get; } = new CustomClass();