2017-06-12 54 views
-1

我想創建一個自定義文本框,當拖動&放入窗體顯示「customTextBox1」,「customTextBox2」就像發生在標籤和按鈕。C#設置自定義文本框的默認文本

我試着這樣做:

public CustomTextBox() 
    { 
     InitializeComponent(); 

     ReadOnly = true; 
     TabStop = false; 
     BorderStyle = BorderStyle.None; 
     Text = "customTextBox"; 
    } 

其他性能做工精細,但表現出我需要建立或拖動customTextBox或文本將保持爲空後啓動該程序的文本和的數量在拖動更多CustomTextBox後,customTextBox不會上升。

注意:我不想要任何PlaceHolder或類似的東西。

回答

0

你的問題是這個線程How would I set the label of my UserControl at design time?的部分重複,但答案,因爲你是從TextBox而不是UserControl繼承和初始化程序有點不同的是不完全適用。根據你的要求,這是不直觀的,這是不幸的,因爲當設計師最初創建它們時,所有的默認文本控件都將它們的Text屬性設置爲它們的Name屬性。

訣竅是爲您的組件實施ControlDesigner(從System.Windows.Forms.Design)。每當窗體上創建一個新的控件時,由WinForms設計器調用一次ControlDesigner.InitializeNewComponent。這是您的機會,可以將Text屬性設置爲Name屬性,而不會對非設計代碼產生副作用,也不會干擾設計器的組件序列化。

我驗證了這個工程的設計者 - 它正確地設置了Text場相匹配的設計師的產生Name場,但一旦控制是由設計師創建了TextName領域保持獨立編輯,就像在默認TextBoxLabel控制。

要做到這一點,您必須添加項目引用到System.Design,這是包含System.Windows.Forms.Design名稱空間的項目。

using System.Collections; 
using System.ComponentModel; 
using System.Windows.Forms; 
using System.Windows.Forms.Design; 

namespace StackOverflowAnswers.CustomControlDefaultText 
{ 
    class CustomTextBoxDesigner : ControlDesigner 
    { 
     public CustomTextBoxDesigner() 
     { 

     } 

     public override void InitializeNewComponent(IDictionary defaultValues) 
     { 
      // Allow the base implementation to set default values, 
      // which are provided by the designer. 
      base.InitializeNewComponent(defaultValues); 

      // Now that all the basic properties are set, we 
      // do our one little step here. Component is a 
      // property exposed by ControlDesigner and refers to 
      // the current IComponent being designed. 
      CustomTextBox myTextBox = Component as CustomTextBox; 
      if(myTextBox != null) 
      { 
       myTextBox.Text = myTextBox.Name; 
      } 
     } 
    } 

    // This attribute sets the designer for your derived version of TextBox 
    [Designer(typeof(CustomTextBoxDesigner))] 
    class CustomTextBox : TextBox 
    { 
     public CustomTextBox() : base() 
     { 
      ReadOnly = true; 
      TabStop = false; 
      BorderStyle = BorderStyle.None; 
     } 
    } 
} 
+0

我發現了三個錯誤 1)ControlDesigner找不到 2)「CustomTextBoxDesigner.InitializeNewComponent(IDictionary的)」:發現重寫 3沒有合適的方法)組分是一種類型,這是無效的在給定的上下文中 – Signum

+0

您是否在我提供的代碼示例的頂部包含了所有'using'語句? – ozeanix

+0

是的,使用System.Windows.Forms.Design;似乎毫無用處,但它在視覺工作室上變成灰色 – Signum