【问题标题】:How can I get Text property to initialize to the objects name at design time?如何让 Text 属性在设计时初始化为对象名称?
【发布时间】:2010-06-10 17:07:11
【问题描述】:

当您从工具箱向表单添加标签时,其文本默认为项目名称(label1label2 等)。如何使用自定义控件实现这一点?到目前为止,我有以下内容,它允许我通过属性窗口更改文本:

private string _text;

[BrowsableAttribute(true)]
public override string Text
{
    get { return _text; }
    set
    {
        _text = value;
        lblID.Text = _text;
    }
}

显然上面的代码按原样工作,但我不知道为什么。 Text 是否自动默认为对象的名称?这个问题仍然适用于不覆盖 Text 的其他属性。

【问题讨论】:

    标签: c# properties attributes custom-controls


    【解决方案1】:
    private string _text = "default value"
    

    【讨论】:

      【解决方案2】:

      查看System.ComponentModel.DefaultValueAttribute

      【讨论】:

      • Label 做“label1”、“label2”的能力是通过它的设计器来处理的。您可以在此处获取相关信息:support.microsoft.com/kb/813808
      【解决方案3】:

      显然,当您从UserControl 继承时,Text 属性会自动设置为对象名称。以下代码有效:

      public partial class CustomControl: UserControl
      {
          public string Extension { get; set; }
      
          private string _text;
      
          [BrowsableAttribute(true)] // Initializes to "customControlN"
          public override string Text
          {
              get { return _text; }
              set { _text = value; }
          }
      }
      

      【讨论】:

      • 那是因为您使用的是默认设计器,它对 Text 属性执行此操作。几乎所有控件都使用默认设计器(或其子类)。如果您反汇编 Label 类,您将在顶部看到:Designer("System.Windows.Forms.Design.LabelDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),LabelDesigner 类的子类 ControlDesigner,它是 ControlDesigner 与 Text 属性一起使用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多