Search code examples
c#winformsvisual-studio-2012user-controlscustom-properties

User Control Custom Property lose value when build


I have a UserControl named "UserControl1" with a label inside it and a custom property:

[Browsable(true)]
public new string Text
{
    get { return label1.Text; }
    set { label1.Text = value; }
}

public UserControl1()
{
    InitializeComponent();
}

This UserControl is used in a form named "Form1". In the designer appears the property but when I write some text and build the application the text is cleared. I can see, the property isn't written in the Form1.Designer.cs.

If I change the property name to some other word all is ok.. Note the "new" keyword to override the base variable..

I have found a similar question here but there is no solution.

Greetings!

EDIT: There is no hardcoded value:

UserControl1.Designer.cs:

        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(64, 63);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(35, 13);
        this.label1.TabIndex = 0;
        // 
        // UserControl1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Controls.Add(this.label1);
        this.Name = "UserControl1";
        this.Size = new System.Drawing.Size(181, 136);
        this.ResumeLayout(false);
        this.PerformLayout();

Form1.Designer.cx:

        // 
        // userControl11
        // 
        this.userControl11.Location = new System.Drawing.Point(35, 43);
        this.userControl11.Name = "userControl11";
        this.userControl11.Size = new System.Drawing.Size(181, 136);
        this.userControl11.TabIndex = 0;
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 262);
        this.Controls.Add(this.userControl11);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);

To reproduce the problem just create a new windows form application, create an user control with a label inside it and with the property named "Text".


Solution

  • Try using override instead of new for the Text property and include the DesignerSerializationVisibility attribute:

    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text {
      get { return label1.Text; }
      set { label1.Text = value; }
    }