Reputation: 6953
I'm trying to create a user control which will allow me to pass in a list of column definitions and which will create a grid for me.
So far nothing is displaying. Here is the code:
List<GridColumn> colList = new List<GridColumn>();
GridColumn col1 = new GridColumn(200, "AAA");
colList.Add(col1);
GridColumn col2 = new GridColumn(200, "BBB");
colList.Add(col2);
BuildColumns(MainGrid, colList)
private void BuildColumns(Grid mainGrid, List<GridColumn> gridColumnList)
{
// create grid columns
foreach (GridColumn gridColumn in gridColumnList)
{
GridLength len = new GridLength(gridColumn.ColumnWidth);
ColumnDefinition col = new ColumnDefinition {Width = len};
mainGrid.ColumnDefinitions.Add(col);
}
// add 2 rows
GridLength height = new GridLength(100);
RowDefinition rowDef1 = new RowDefinition {Height = height};
mainGrid.RowDefinitions.Add(rowDef1);
RowDefinition rowDef2 = new RowDefinition {Height = height};
mainGrid.RowDefinitions.Add(rowDef2);
// add text blocks to cells
int colNum = -1;
foreach (GridColumn gridColumn in gridColumnList)
{
colNum++;
TextBlock textBlock = new TextBlock();
textBlock.Text = gridColumn.ColumnName;
Grid.SetRow(textBlock, 0);
Grid.SetColumn(textBlock, colNum);
}
}
I have tried increasing the row/column size and refreshing the grid.
This is the same as this earlier question but the answer did not fix my problem.
This is what it looks like on the phone
Upvotes: 2
Views: 4191
Reputation: 16319
The problem is that you aren't actually adding the TextBlock
elements into the visual tree. You need to add them to the Children
collection on the mainGrid Grid
element supplied to the BuildColumns
method.
private void BuildColumns(Grid mainGrid, List gridColumnList)
{
// create grid columns
foreach (GridColumn gridColumn in gridColumnList)
{
GridLength len = new GridLength(gridColumn.ColumnWidth);
ColumnDefinition col = new ColumnDefinition { Width = len };
mainGrid.ColumnDefinitions.Add(col);
}
// add 2 rows
GridLength height = new GridLength(100);
RowDefinition rowDef1 = new RowDefinition {Height = height};
mainGrid.RowDefinitions.Add(rowDef1);
RowDefinition rowDef2 = new RowDefinition {Height = height};
mainGrid.RowDefinitions.Add(rowDef2);
// add text blocks to cells
int colNum = -1;
foreach (GridColumn gridColumn in gridColumnList)
{
colNum++;
TextBlock textBlock = new TextBlock();
textBlock.Text = gridColumn.ColumnName;
Grid.SetRow(textBlock, 0);
Grid.SetColumn(textBlock, colNum);
mainGrid.Children.Add(textBlock); // This line makes all the difference.
}
}
Upvotes: 4