简体   繁体   中英

Text property in a UserControl in C#

I have a control with a inner TextBox. I want to make a direct relationship between the Text property of the UserControl and the Text property of the TextBox. The first thing I realized is that Text was not being displayed in the Properties of the UserControl. Then I added the Browsable(true) attribute.

[Browsable(true)]
public override string Text
{
    get
    {
        return m_textBox.Text;
    }

    set
    {
        m_textBox.Text = value;
    }
}

Now, the text will be shown for a while, but then is deleted. This is because the information is not written automatically within the xxxx.Designer.cs file. How can this behviour be changed?

You need more attributes:

[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Bindable(true)]
public override string Text { get; set; }

Reflector is a crucial tool for a .NET developer. It is immediately obvious what you need to do when you use it to look at the UserControl.Text property:

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

Ho showed you what you need to do to cancel these attributes, too bad he didn't show you how he found out. Reflector is was free, download it from redgate.com or check the alternatives here : Something Better than .NET Reflector?

为了在InitializeComponent()进行序列化,您需要的是DesignerSerializationVisibilityAttribute

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM