在WP7上以编程方式创建Silverlight Grid列的问题

时间:2011-02-21 02:47:35

标签: silverlight windows-phone-7 grid

我正在尝试创建一个用户控件,它允许我传入一个列定义列表,这将为我创建一个网格。

到目前为止还没有显示出来。这是代码:

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相同,但答案并没有解决我的问题。

这就是手机上的样子

enter image description here

1 个答案:

答案 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.
    }
}