2012-09-27 83 views
0

比方說,我們有下面的類Cell,它是由一個Label控制:更改動態創建的自定義控件的位置

class Cell : UserControl 
{ 
    Label base; 

    public Cell(Form form) 
    { 
     base = new Label(); 
     base.Parent = form;   
     base.Height = 30; 
     base.Width = 30; 
    } 
} 

public partial class Form1 : Form 
{ 
    Label label = new Label(); 

    public Form1() 
    { 
     InitializeComponent(); 

     Cell cell = new Cell(this); 
     cell.Location = new Point(150, 150); //this doesnt work    
     label.Location = new Point(150,150); //but this does 
    } 
} 

Cell將在Form顯示,而是固定在top left (0,0)位置。

將位置屬性設置爲一個新的Point與任何其他座標什麼也不做,因爲Cell將保留在左上角。

但是,如果一個人創建一個新Label,然後嘗試將其位置,標籤會被感動。

有沒有辦法做到這一點我Cell對象?

+0

你控件添加到控件集合?你用對接嗎? –

回答

1

我覺得你的主要問題是,你沒有正確添加控件的容器。

首先,您需要將內標籤添加到細胞;

class Cell : UserControl 
{  
    Label lbl; 

    public Cell() 
    { 
     lbl = new Label(); 
     lbl.Parent = form;   
     lbl.Height = 30; 
     lbl.Width = 30; 
     this.Controls.Add(lbl); // label is now contained by 'Cell' 
    } 
} 

然後,您需要將單元格添加到窗體;

Cell cell = new Cell(); 
form.Controls.Add(cell); 

另外; 'base'是一個保留字,所以你不能命名這樣的內部標籤控件。

+0

謝謝,這個作品!你能不能幫我在表格中顯示一系列這些單元格?這樣一個300×300的表單區域可以填充30×30個單元格來形成一個網格?我現在可以創建並顯示多個單元格,但它幾乎就好像每個單元格都有大面積的空白區域,使其他區域模糊不清。 – user1701826

+0

編輯:只是想出瞭如何做到這一點。這只是使用Cell.BringToFront()將每個新的Cell對象放在前面的問題 – user1701826

0

試試這個:

class Cell : Label 
    { 

    public Cell(Form form) 
     { 

       this.Parent = form;   
      this.Height = 30; 
      this.Width = 30; 
     } 
    } 


    public partial class Form1 : Form 
    { 
     Label label = new Label(); 


     public Form1() 
     { 
      InitializeComponent(); 


      Cell cell = new Cell(this); 

      cell.Location = new Point(150, 150); //this doesnt work 

      label.Location = new Point(150,150); //but this does 

     } 
+0

有什麼區別? –

+0

區別在於,這對我有用 –

+0

但它不會做同樣的事情。它公開所有標籤功能,並且不能向用戶控件添加更多控件。 –