简体   繁体   English

C#中的UserControl中的Text属性

[英]Text property in a UserControl in C#

I have a control with a inner TextBox. 我有一个带有内部TextBox的控件。 I want to make a direct relationship between the Text property of the UserControl and the Text property of the TextBox. 我想在UserControl的Text属性和TextBox的Text属性之间建立直接关系。 The first thing I realized is that Text was not being displayed in the Properties of the UserControl. 我意识到的第一件事是Text没有显示在UserControl的属性中。 Then I added the Browsable(true) attribute. 然后,我添加了Browsable(true)属性。

[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. 这是因为该信息不会自动写入xxxx.Designer.cs文件中。 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. Reflector是.NET开发人员的重要工具。 It is immediately obvious what you need to do when you use it to look at the UserControl.Text property: 当您使用它查看UserControl.Text属性时,很明显您需要执行的操作:

[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. Ho向您展示了取消这些属性所需的操作,很可惜,他没有向您展示如何找到这些属性。 Reflector is was free, download it from redgate.com or check the alternatives here : Something Better than .NET Reflector? Reflector 免费的,可以从redgate.com下载它,或在此处查看替代方法: 比.NET Reflector更好的东西吗?

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

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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