我正在尝试根据用户输入的行数和列数创建按钮网格,并且创建网格的方法不起作用。当我调用它时,网格不会被创建。
该方法在我的TileClass中,我试图以我的GameBoard形式调用它。我觉得我没有正确使用这门课程。我认为我没有正确地调用该方法,因为我认为这应该有效。
This is what the form looks like
class TileClass : Button
{
public const int LEFT = 20;
public const int WIDTH = 50;
public const int HEIGHT = 50;
public const int TOP = 50;
public const int VGAP = 30;
public int x;
public int y;
public int column;
public int row;
private int incomingRow;
private int incomingColumn;
public int IncomingRow { get => incomingRow; set => incomingRow = value; }
public int IncomingColumn { get => incomingColumn; set => incomingColumn = value; }
public TileClass()
{
}
public void CreateGrid()
{
x = LEFT;
y = TOP;
column = IncomingColumn;
row = IncomingRow;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
Button b = new Button();
b.Left = x;
b.Top = y;
b.Width = WIDTH;
b.Height = HEIGHT;
b.Text = j.ToString();
x += VGAP + HEIGHT;
this.Controls.Add(b);
}
}
}
}
游戏板表格
public partial class GameBoard : Form
{
TileClass tileClass = new TileClass();
public GameBoard()
{
InitializeComponent();
}
private void txtEnter_Click(object sender, EventArgs e)
{
tileClass.IncomingColumn = int.Parse(txtColumn.Text);
tileClass.IncomingRow = int.Parse(txtRow.Text);
tileClass.CreateGrid();
}
答案 0 :(得分:1)
要实现这一目标还有很多工作要做:
class TileClass : Panel
{
...
public int IncomingRow {get; set;}
public int IncomingColumn { get; set; }
...
}
并删除:
private int incomingRow;
private int incomingColumn;
并且理想的方法是在添加按钮之前使用ResumeLayout,并通过调用Invalidate让Gameboard表单重绘。 What does invalidate method do? 注意:尝试col = 100,row = 100,有和没有ResumeLayout&amp; Invalidate
public partial class GameBoard : Form
{
public GameBoard ()
{
InitializeComponent();
tileClass.Dock = DockStyle.Fill;
this.Controls.Add(tileClass);
}
TileClass tileClass = new TileClass();
private void txtEnter_Click(object sender, EventArgs e)
{
tileClass.IncomingColumn = int.Parse(txtColumn.Text);
tileClass.IncomingRow = int.Parse(txtRow.Text);
this.ResumeLayout(); //Important
tileClass.CreateGrid();
this.Invalidate(); // Important
}
}
你可以设置更多属性,它需要的不仅仅是:
//tileClass.Location = new Point(10, 10); // not sure
tileClass.Dock = DockStyle.Fill;
//tileClass.Size = new Size(200, 200); // not sure
而不是j&lt; 5你应该使用col和row:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
Button b = new Button();
b.Left = x;
b.Top = y;
b.Width = WIDTH;
b.Height = HEIGHT;
b.Text = string.Format("({0},{1})" , i, j);
x += VGAP + HEIGHT;
this.Controls.Add(b);
}
x = LEFT; // not sure, plz calculate!
y += Top * (i+1); // not sure, plz calculate!
}