Search code examples
c#gridviewwindows-runtimetextblock

Adding textblocks of variying height to gridview c# winrt


I am trying to add several textblocks that contain text of varying lengths to a gridview. I want to adjust the height and width properties so that the text in the textblocks can be visible. The problem is when the program runs, all the textblock items have the same height. The width is as i specified but the height is not the value i assigned. What am i missing?

GridView grdvMain = new GridView();
List<TextBlock> tList = new List<TextBlock>;

for (int i =0; i < paragraphs.Length; i++)
{
    if (paragraphs[i].Trim() == "")
        continue;

    double height = (paragraphs[i].Trim().Split(' ').Length / 5.0) * 30;
    tList.Add(
        new TextBlock() 
        {
            TextWrapping = TextWrapping.Wrap, 
            Text = paragraphs[i].Trim(), 
            Width = 300, 
            Height = height ,
            Foreground = new SolidColorBrush(Windows.UI.Colors.Black),
            FontSize = 20
        });
}

grdvMain.ItemsSource = tList;

Solution

  • The items in ListView or GridView always have same height. It is usually based on the calculated height of the first item, but you can also set it by specifying ItemHeight of the ItemsPanel defined for the ItemsControl (e.g. ListView or GridView).

    You can use VariableSizedWrapGrid to be able to define how many grid columns/rows a cell spans, but the purpose of it is more to feature some items and not to extend all items to fit all text.

    If your maximum text length is limited - you can make all items the size that will fit any text or you can trim the text if it doesn't fit and display it all once a grid view item is tapped and you navigate to the detailed view of the item.