【问题标题】:User Control Custom Property lose value when build用户控件自定义属性在构建时失去价值
【发布时间】:2013-07-07 19:22:17
【问题描述】:

我有一个名为“UserControl1”的用户控件,里面有一个标签和一个自定义属性:

[Browsable(true)]
public new string Text
{
    get { return label1.Text; }
    set { label1.Text = value; }
}

public UserControl1()
{
    InitializeComponent();
}

此用户控件在名为“Form1”的表单中使用。 在设计器中出现该属性,但是当我编写一些文本并构建应用程序时,文本被清除。可以看到,Form1.Designer.cs中没有写属性。

如果我将属性名称更改为其他单词,一切正常。请注意“new”关键字以覆盖基本变量。

我发现了一个类似的问题here,但没有解决方案。

您好!

编辑:没有硬编码值:

UserControl1.Designer.cs:

        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(64, 63);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(35, 13);
        this.label1.TabIndex = 0;
        // 
        // UserControl1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Controls.Add(this.label1);
        this.Name = "UserControl1";
        this.Size = new System.Drawing.Size(181, 136);
        this.ResumeLayout(false);
        this.PerformLayout();

Form1.Designer.cx:

        // 
        // userControl11
        // 
        this.userControl11.Location = new System.Drawing.Point(35, 43);
        this.userControl11.Name = "userControl11";
        this.userControl11.Size = new System.Drawing.Size(181, 136);
        this.userControl11.TabIndex = 0;
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 262);
        this.Controls.Add(this.userControl11);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);

要重现该问题,只需创建一个新的 Windows 窗体应用程序,创建一个用户控件,其中包含一个标签和名为“Text”的属性。

【问题讨论】:

  • 你能澄清一下...when I write some text and build the application the text is cleared...吗?代码是什么,你把它放在课堂上的什么位置?
  • 嗨,我的意思是,当我在设计器视图中编写一些字符串时。它出现在标签中(在设计器视图中),但是当我运行应用程序(构建)时,文本消失了。相应的代码应该出现在 Form1.Designer.cs 中。类似这样:this.userControl11.Text = "asdf";但是没有..

标签: c# winforms visual-studio-2012 user-controls custom-properties


【解决方案1】:

尝试使用 override 而不是 new 作为 Text 属性并包含 DesignerSerializationVisibility 属性:

[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return label1.Text; }
  set { label1.Text = value; }
}

【讨论】:

    【解决方案2】:

    查看 InitializeComponent() 内部。当您将控件放在设计图面上时,很可能是硬编码默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 2012-02-18
      • 2011-08-19
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多