gpt4 book ai didi

c# - 如何通过在类中创建的方法在表单上创建按钮?

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:07 26 4
gpt4 key购买 nike

我正在尝试根据用户输入的行数和列数创建按钮网格,但我创建网格的方法不起作用。当我调用它时,不会创建网格。

该方法在我的 TileClass 中,我试图在我的 GameBoard 表单中调用它。我觉得我没有正确使用类(class)。我认为我没有正确调用该方法,因为我认为这应该有效。

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();

}

最佳答案

要实现这一目标还有很多工作要做:

class TileClass : Panel
{
...
public int IncomingRow {get; set;}
public int IncomingColumn { get; set; }
...
}

并删除:

private int incomingRow;
private int incomingColumn;

理想的方法是在添加按钮之前使用 ResumeLayout,并通过调用 Invalidate 重绘游戏板表单。 What does invalidate method do?注意:尝试使用和不使用 ResumeLayout&Invalidate 的 col=100, row=100

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 < 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!
}

关于c# - 如何通过在类中创建的方法在表单上创建按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46720978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com