Text of UserControl dissappears in designer after

2019-07-19 13:18发布

问题:

I have the wierdest thing going on in my solution. I have a button, which I customly made. It inherits UserControl, and its text is represented as a Label inside that control.

Naturally, I wanted the button's text to be overridden to set the Label's text:

Either,

    /// <summary>
    /// Gets or sets the text that appears in the button
    /// </summary>
    [Category("Appearance"), Description("Gets or sets the text on the button.")]
    [Browsable(true)]
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = value;
            labelButtonText.Text = value;
        }
    }

Or

    /// <summary>
    /// Gets or sets the text that appears in the button
    /// </summary>
    [Category("Appearance"), Description("Gets or sets the text on the button.")]
    [Browsable(true)]
    public override string Text
    {
        get
        {
            return labelButtonText.Text ;
        }
        set
        {
            labelButtonText.Text = value;
        }
    }

Regardless of the method, when I use that button in another UserControls/Forms, the text I explicitly put inside in the designer dissappears after compilation.

I checked in the "Button.designer.cs" file, and there is no assignment of the text to null nor empty for neither the UserControl nor the Label.

EDIT: Moreover, when I set the Text property in the designer, it does not set in the *.designer.cs file.

Thanks in advance.

回答1:

Yes, this is by design. The UserControl.Text property looks like this:

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Bindable(false)]
public override string Text
{
    get
    {
        return base.Text;
    }
    set
    {
        base.Text = value;
    }
}

You took care of the [Browsable] attribute but not the [DesignerSerializationVisibility]. Hidden is what makes the text disappear. Fix it by undo-ing all of the attributes:

    [Browsable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    [Bindable(true)]
    public override string Text {
        // etc..
    }