Text property in a UserControl in C#

喜欢而已 提交于 2019-12-17 07:25:09

问题


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?


回答1:


You need more attributes:

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



回答2:


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?




回答3:


For serialization within the InitializeComponent(), all you need is the DesignerSerializationVisibilityAttribute:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]


来源:https://stackoverflow.com/questions/2881409/text-property-in-a-usercontrol-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!