2

我有一個名爲「的UserControl1」裏面坐了一個標籤和一個自定義屬性用戶控件:用戶控制自定義屬性失去價值時構建

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

public UserControl1() 
{ 
    InitializeComponent(); 
} 

該用戶控件在一個名爲「Form1的」形式使用。 在設計器中出現屬性,但是當我編寫一些文本並構建應用程序時,文本被清除。我可以看到,該屬性不是寫在Form1.Designer.cs中的。

如果我更改屬性名稱到一些其他的字全部是確定..請注意「新」的關鍵字覆蓋基本變量..

我發現了一個類似的問題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」的屬性創建一個用戶控件。

+0

你能澄清這個'...當我寫一些文字,並建立文本被清除的應用... '?什麼是代碼,以及你把它放在你的課堂上? –

+0

嗨,我的意思是,當我在設計器視圖中寫入一些字符串時。它出現在標籤中(在設計器視圖中),但是當我運行應用程序(構建)時,文本消失。相應的代碼應該出現在Form1.Designer.cs ..像這樣:this.userControl11.Text =「asdf」;但是沒有.. – elecyb

回答

4

嘗試使用override代替new Text屬性和包括DesignerSerializationVisibility屬性:

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

解決了這個問題! 謝謝。 – elecyb

1

Look inside InitializeComponent()。將控件放置在設計圖面上時,很可能會對默認值進行硬編碼。

相關問題