You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF中用for循环创建网格按钮却不显示的问题

四子棋棋盘按钮不显示的问题修复

你的代码里有几个关键错误导致按钮无法正常显示,逐个修复即可:

1. CreateBoard方法内层循环增量错误

这是按钮不显示的核心原因:你在CreateBoard的内层for循环中,错误地把循环增量写成了column++,而不是col++。这个错误会让column的值持续增大,循环条件col < column永远成立,要么程序卡死在循环里,要么创建的按钮列索引越界,根本无法正常添加到Grid中。

修复后的CreateBoard方法:

private void CreateBoard(int columnCount, int rowCount)
{
    for (var row = 0; row < rowCount; row++)
    {
        // 内层循环改为col++,使用循环变量col递增
        for (var col = 0; col < columnCount; col++)
        {
            Button button = new Button();
            {
                var brush = new ImageBrush();
                brush.ImageSource = new BitmapImage(new Uri("gridsingle.png.bmp", UriKind.Relative));
                button.Background = brush;
                // 给按钮自身的Name属性赋值,避免错误修改窗口名称
                button.Name = "btn_" + row + "_" + col;
            };
            button.Click += Btn_Click;
            Grid.SetRow(button, row);
            Grid.SetColumn(button, col);
            myGrid.Children.Add(button);
        }
    }
}

2. BoardArray初始化循环的增量错误

构造函数中初始化棋盘数组的内层循环,错误地使用了loopColumn++作为增量,正确应该是loopRow++。这个错误会导致只给数组的第一行重复赋值,虽然不影响按钮显示,但会导致后续棋盘逻辑出错。

修复后的初始化循环:

for (int loopColumn = 0; loopColumn <= 6; loopColumn++)
{
    for (int loopRow = 0; loopRow <= 5; loopRow++)
    {
        BoardArray[loopRow, loopColumn] = 0;
    }
}

3. 额外的数组维度问题

你的BoardArray声明为new int[5, 6],但实际棋盘是6行7列,数组维度不足会导致后续操作出现索引越界异常,建议修改为:

public int[,] BoardArray = new int[6, 7];

把这些错误修复后,按钮应该就能正常显示在界面上了。

内容的提问来源于stack exchange,提问作者Sreyas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:01:05