2014-03-02 33 views
1

嗨我正在使用下面的代码来动态生成WPF应用程序中的文本框。N-1回路元素丢失

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

+0

我不知道WPF,但我的循环似乎没事,是有可能,一个rowdefination可以通过其他被overlaped ? –

回答

2

Grid.RowGrid.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); 
    } 
} 
+0

非常感谢您的回答,我不知道我是如何错过的,如果我缺少第九排,问题会很明显,但我错过了最后一个.. – robot

+1

不客气。看起来,如果你使用SetRow()来设置行数大于最大行定义的行数,那么WPF会将该对象放在最后一行,因此你得到的第9行与第8行相同(最大行数为8,基于零)。如果没有事先知道它的行为就很难预测,所以使用Snoop就像我在这个答案中提到的那样对于这种情况很有用。 – har07