如何在c#中创建和管理按钮矩阵

本文关键字:管理 按钮 创建 | 更新日期: 2023-09-27 17:49:22

我有一个20x23位的矩阵。
我需要在winform (GUI)中表示这个矩阵。
其思想是,用户将能够通过单击表示矩阵中特定单元格的相关按钮来更改特定单元格的内容。(当用户点击按钮时,矩阵中相应的位元被反转)

我考虑过使用GRID,但由于GUI(设计)问题,不可能使用它。

如何有效地创建和管理20x23(=460)按钮,并使其与实际矩阵相关联?

如何在c#中创建和管理按钮矩阵

这并不难,我将从一个为您生成按钮矩阵的方法开始。这个矩阵由按钮组成,其中ID(即。标记)将对应于正确的cellNumber(您也可以考虑将坐标作为Point实例传递,我将留给您决定)。

基本上,它是这样的,所有的按钮都呈现在一个面板(panel1):

...
#region Fields
//Dimensions for the matrix
private const int yDim = 20;
private const int xDim = 23;
#endregion
...
private void GenerateButtonMatrix()
{
  Button[,] buttonMatrix = new Button[yDim, xDim];
  InitializeMatrix(ref matrix);  //Corresponds to the real matrix
  int celNr = 1;
  for (int y = 0; y < yDim; y++)
  {
    for (int x = 0; x < xDim; x++)
    {
      buttonMatrix[y,x] = new Button()
        {
          Width = Height = 20,
          Text = matrix[y, x].ToString(),
          Location = new Point( y * 20 + 10, 
                                x * 20 + 10),  // <-- You might want to tweak this
          Parent = panel1,
        };
      buttonMatrix[y, x].Tag = celNr++;
      buttonMatrix[y,x].Click += MatrixButtonClick;
    }
  }
}

正如你所看到的,所有460个按钮都有一个自定义的eventandler连接到ClickEvent,称为MatrixButtonClick()。这个事件处理程序将处理ClickEvent,并可能确定用户单击了哪个按钮。通过再次检索标签,您可以计算出与"实"矩阵对应的正确坐标。

private void MatrixButtonClick(object sender, EventArgs e)
{
  if (sender is Button)
  {
    Button b = sender as Button;
    //The tag contains the cellNr representing the cell in the real matrix
    //To calculate the correct Y and X coordinate, use a division and modulo operation
    //I'll leave that up to you :-)
    .... Invert the real matrix cell value
  }
}

我不会把所有的东西都给你,因为这对你来说是一个很好的练习:)。

我将:
1)创建一个具有所需属性的对象
2)填充列表并填充值
3)迭代列表创建按钮,并分配其点击处理程序和按钮的名称(如名称button_rowindex_colindex)
4)在点击处理程序中,通过检测哪个按钮被点击来给对象单元格赋值