更改动态创建的自定义控件的位置



假设我们有以下类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)位置。

将 Location 属性设置为具有任何其他坐标的新Point不会执行任何操作,因为Cell将保留在左上角。

但是,如果要创建新Label,然后尝试设置其位置,则会移动标签。

有没有办法在我的Cell对象上执行此操作?

我认为您的主要问题是您没有正确将控件添加到容器中。

首先,您需要将内部标签添加到单元格;

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"是一个保留字,因此不能将内部标签控件命名为此类。

试试这个:

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
        }

最新更新