2012-02-01 110 views
1

你好創建一個自定義對象可能是一個廣泛發佈的主題,但我缺乏編碼技巧證明在實際執行我想要做的事情時存在問題。創建自定義對象(兩個對象的組合)

簡而言之,我在運行時在flowpanelLayout中添加了控件。現在它只是列表框,代碼工作正常。我想要一種方法來標記正在添加的列表框,我想不出一個更好的方式來做到這一點,而不是使用文本標籤。我認爲創建某種自定義控件(如果可能的話)是很靈活的,這是一個列表框和一個文本標籤,比如一個在另一個之上。通過這種方式,我可以在當前代碼中添加新的自定義控件,並將列表框屬性和標籤文本等全部分配到一個動作中。

這就是我在想什麼,也許還有更好的方法來做到這一點。

我當前的ListView創建代碼:

public void addListView() 
     { 

      ListView newListView = new ListView(); 
      newListView.AllowDrop = true; 
      newListView.DragDrop += listView_DragDrop; 
      newListView.DragEnter += listView_DragEnter; 
      newListView.MouseDoubleClick += listView_MouseDoubleClick; 
      newListView.MouseDown += listView_MouseDown; 
      newListView.DragOver += listView_DragOver; 
      newListView.Width = 200; 
      newListView.Height = 200; 
      newListView.View = View.Tile; 
      newListView.MultiSelect = false; 

      flowPanel.Controls.Add(newListView); 
      numWO++; 

      numberofWOLabel.Text = numWO.ToString(); 
     } 

也許實際的最好的答案很簡單,就是在這裏也加爲textLabel和定義一些設置的座標把它。讓我知道你的想法。

如果自定義控件是要走的路,請爲我提供一些資源或示例 - 我會很感激。

回答

1

這是一個自定義用戶控件,可以這樣做: 您只需要設置TitleLabelText來設置標題。

[Category("Custom User Controls")] 
public class ListBoxWithTitle : ListBox 
{ 
    private Label titleLabel; 
    public ListBoxWithTitle() 
    { 
     this.SizeChanged +=new EventHandler(SizeSet); 
     this.LocationChanged +=new EventHandler(LocationSet); 
     this.ParentChanged += new EventHandler(ParentSet); 

    } 
    public string TitleLabelText 
    { 
     get; 
     set; 
    } 
    //Ensures the Size, Location and Parent have been set before adding text 
    bool isSizeSet = false; 
    bool isLocationSet = false; 
    bool isParentSet = false; 
    private void SizeSet(object sender, EventArgs e) 
    { 
     isSizeSet = true; 
     if (isSizeSet && isLocationSet && isParentSet) 
     { 
      PositionLabel(); 
     } 
    } 
    private void LocationSet(object sender, EventArgs e) 
    { 
     isLocationSet = true; 
     if (isSizeSet && isLocationSet && isParentSet) 
     { 
      PositionLabel(); 
     } 
    } 
    private void ParentSet(object sender, EventArgs e) 
    { 
     isParentSet = true; 
     if (isSizeSet && isLocationSet && isParentSet) 
     { 
      PositionLabel(); 
     } 
    } 
    private void PositionLabel() 
    { 
     //Initializes text label 
     titleLabel = new Label(); 
     //Positions the text 10 pixels below the Listbox. 
     titleLabel.Location = new Point(this.Location.X, this.Location.Y + this.Size.Height + 10); 
     titleLabel.AutoSize = true; 
     titleLabel.Text = TitleLabelText; 
     this.Parent.Controls.Add(titleLabel); 
    } 

} 

使用例:

public Form1() 
    { 
     InitializeComponent(); 

     ListBoxWithTitle newitem = new ListBoxWithTitle(); 
     newitem.Size = new Size(200, 200); 
     newitem.Location = new Point(20, 20); 
     newitem.TitleLabelText = "Test"; 
     this.Controls.Add(newitem); 
    } 
+0

正是我一直在尋找。謝謝。 – ikathegreat 2012-02-01 00:59:32