我正在尝试创建一个用户控件,它允许我传入一个列定义列表,这将为我创建一个网格。
到目前为止还没有显示出来。这是代码:
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);
}
}
我尝试过增加行/列大小并刷新网格。
这与this earlier question相同,但答案并没有解决我的问题。
这就是手机上的样子
答案 0 :(得分:4)
问题是您实际上并未将TextBlock
元素添加到可视树中。您需要将它们添加到Children
方法提供的 mainGrid Grid
元素的BuildColumns
集合中。
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.
}
}