简体   繁体   English

自定义控件重写文本属性默认值

[英]Custom Control Overridden Text Property Default Value

I have created a user control that has a textbox inside of it. 我创建了一个用户控件,里面有一个文本框。 I have overridden the Text property of the base control like the following: 我已经覆盖了基本控件的Text属性,如下所示:

    [Browsable(true)]
    [DefaultValue("")]
    [Description("Test1"), Category("Test")]
    public new string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text= value;
        }
    }

Now, I am having this issue where any instances i create of the control in a form, the Text always have a value of the controlname + number (of instance). 现在,我遇到这个问题,我在表单中创建控件的任何实例,Text始终具有controlname + number(实例)的值。 I want to know why is this happening, and how to remove this default value? 我想知道为什么会发生这种情况,以及如何删除此默认值? Thanks. 谢谢。

Initial hunch is that it is calling ToString() on the object. 最初的预感是它在对象上调用ToString() Override ToString() to return your desired value. 覆盖ToString()以返回所需的值。

The attribute DefaultValue does not set the default value. DefaultValue属性未设置默认值。 The attribute is for describing what the default value is. 该属性用于描述默认值。 You have to set the default value yourself, and then use the attribute to describe it. 您必须自己设置默认值,然后使用该属性来描述它。

So in your example, textbox1.Text must be populated with the control id. 因此,在您的示例中,必须使用控件ID填充textbox1.Text。 On your UserControl, in OnInit or wherever appropriate, you should call 在您的UserControl上,在OnInit或任何适当的地方,您应该打电话

this.Text = "";
[DefaultValue("")]
public override string Text
{
    get { return base.Text; }
    set
    {
        if (this.DesignMode && (Environment.StackTrace.Contains("System.Windows.Forms.Design.ControlDesigner.InitializeNewComponent")))
            return;
        base.Text = value; 
        Invalidate();
    }
}

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

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