Search code examples
c#winformsvisual-studio-2012custom-controlsdesigner

Custom control properties for an internal TextBox


Consider a custom control that has a property Rows:

private EMRow[] _rows;

public CustControl()
{
    InitializeComponent();
}

public EMRow[] Rows
{
    get
    {
        return _rows;
    }
    set
    {
        _rows = value;
    }
}

Each EMRow creates a TextBox and exposes two properties, one for the Text and one for the control itself:

private TextBox _txtValue;

public EMRow()
{
    if (_txtValue == null)
        _txtValue = new TextBox();
}

public string Value
{
    get
    {
        return _txtValue.Text;
    }
    set
    {
        _txtValue.Text = value;
    }
}

public TextBox ValueTextBox
{
    get
    {
        return _txtValue;
    }
    set
    {
        _txtValue = value;
    }
}

If you drop this custom control onto a form and modify the Value property, it updates and safes the changes to the designer.cs file.

When you drill down into the ValueTextBox properties (again, all of this in visual studio designer, not code) and modify a property the changes are NOT saved to the designer.cs file. As far as the designer is concerned, there isn't even a TextBox object created and referenced to this property.

I'm sure this is 'as expected' behavior but I'm stumped as to why. Am I missing a fundamental for VS designer here?


Solution

  • After some digging I found the solution to this problem, tell the designer to serialize this object itself by adding the DesignerSerializationVisibility attribute

    private TextBox _txtValue;
    
    public EMRow()
    {
        if (_txtValue == null)
            _txtValue = new TextBox();
    }
    
    public string Value
    {
        get
        {
            return _txtValue.Text;
        }
        set
        {
            _txtValue.Text = value;
        }
    }
    
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public TextBox ValueTextBox
    {
        get
        {
            return _txtValue;
        }
        set
        {
            _txtValue = value;
        }
    }    
    

    Winforms Designer: Modify (and keep) properties in sub objects Thanks Hans!