假设我们有以下课程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
对象上执行此操作?
答案 0 :(得分:1)
我认为您的主要问题是您没有正确地将控件添加到容器中。
首先,您需要将内部标签添加到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'是保留字,因此您不能将内部标签控件命名为。
答案 1 :(得分: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
}