您好我正在使用以下代码动态生成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行。这很奇怪..你能告诉我我做错了吗?
答案 0 :(得分:2)
Grid.Row
开始时, Grid.Column
和_row = 1
附加属性从零开始。因此,您没有使用row=0
,并且您没有row=9
。
如果您在运行时使用Snoop检查Grid
,则会显示第9行与第8行重叠。尝试将代码更改为从row=0
和column=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);
}
}