缺少第N-1个循环元素

时间:2014-03-02 05:09:17

标签: c# wpf for-loop wpf-controls

您好我正在使用以下代码动态生成WPF Applicaiton中的文本框。

    for (int _row = 1; _row < 10; _row++)
        {
            RowDefinition rowDef = new RowDefinition();
            if ((_row == 4) || (_row == 7))
            {
                rowDef.Height = new GridLength(35);
            }
            else
            {
                rowDef.Height = new GridLength(30);
            }
            grdMain.RowDefinitions.Add(rowDef);

            for (int _col = 1; _col < 10; _col++)
            {

                ColumnDefinition coldef = new ColumnDefinition();
                if (_col == 4 || _col == 7)
                    coldef.Width = new GridLength(35);
                else
                    coldef.Width = new GridLength(30);
                grdMain.ColumnDefinitions.Add(coldef);

                TextBox tb = new TextBox();
                tb.Name = "txt" + _row.ToString() + _col.ToString();
                tb.MaxLength = 2;
                tb.Text = _row.ToString() + _col.ToString();
                tb.Width = 30;
                tb.Height = 30;

                grdMain.Children.Add(tb);

                Grid.SetRowSpan(tb, 1);
                Grid.SetColumnSpan(tb, 1);

                Grid.SetRow(tb, _row);
                Grid.SetColumn(tb, _col);
            }
        }

正在添加控件,但只缺少第8行。这很奇怪..你能告诉我我做错了吗?

Here is the Image

1 个答案:

答案 0 :(得分:2)

当您的循环从Grid.Row开始时,

Grid.Column_row = 1附加属性从零开始。因此,您没有使用row=0,并且您没有row=9

如果您在运行时使用Snoop检查Grid,则会显示第9行与第8行重叠。尝试将代码更改为从row=0column=0开始,如下所示:

Grid.SetRow(tb, _row-1);
Grid.SetColumn(tb, _col-1);

然后相应地调整if条件。

另一个调整,使用当前代码,您有9x9列定义,这是一个巨大的浪费。移动for循环用于在for循环之外创建列定义以创建行定义(放在之前):

for (int _col = 1; _col < 10; _col++)
{

    ColumnDefinition coldef = new ColumnDefinition();
    if (_col == 4 || _col == 7)
        coldef.Width = new GridLength(35);
    else
        coldef.Width = new GridLength(30);
    grdMain.ColumnDefinitions.Add(coldef);
}
for (int _row = 1; _row < 10; _row++)
{
    RowDefinition rowDef = new RowDefinition();
    if ((_row == 4) || (_row == 7))
    {
        rowDef.Height = new GridLength(35);
    }
    else
    {
        rowDef.Height = new GridLength(30);
    }
    grdMain.RowDefinitions.Add(rowDef);

    for (int _col = 1; _col < 10; _col++)
    {
        TextBox tb = new TextBox();
        tb.Name = "txt" + _row.ToString() + _col.ToString();
        tb.MaxLength = 2;
        tb.Text = _row.ToString() + _col.ToString();
        tb.Width = 30;
        tb.Height = 30;

        grdMain.Children.Add(tb);

        Grid.SetRowSpan(tb, 1);
        Grid.SetColumnSpan(tb, 1);

        Grid.SetRow(tb, _row-1);
        Grid.SetColumn(tb, _col-1);
    }
}