0

In my application, there are ten textboxes child to Stack panel. I assigning text to textboxes in the Main Window function of c# script. I want to calculate the total height of the textboxes.

The problem is it is giving 0. Please look into the code below:

List<TextInfoData> newList = new List<TextInfoData>();

public MainWindow()
{
    InitializeComponent();

    for (int num = 0; num < 10; num++)
    {
        newList.Add(new TextInfoData("Sunset is the time of day when our sky meets the " +
            "outer space solar winds. There are blue, pink, and purple swirls, spinning " +
            "and twisting, like clouds of balloons caught in a blender.", 1));
    }

    RearrangeTextData(newList);
}

private void RearrageTextData(List<TextInfoData> textInfoData)
{

    TextBox tbox = new TextBox();
    //rest of code to define textbox margin and setting textwrapping to wrap

    double totalTextBoxHeight = 0;

    foreach (TextInfoData tinfoData in textInfoData)
    {
        tbox.Text = tinfoData.GetTextDataString();
        totalTextBoxHeight += tbox.ActualHeight;
        rootStackPanel.Children.Add(tbox);
    }

    MessageBox.Show("Total Height: " + totalTextBoxHeight);
}

I have a class TextInfoData which accepts string and integer two values as parameter. There is function GetTextDataString, which returns the string value.

The name of parent stack panel is rootStackPanel.

If I check total number of children of rootStackPanel, it is showing ten (which is right) but when I try to get total text box height, it gives 0. Please guide me.

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Kumar Sree
  • 11
  • 3
  • Possible duplicate of [When text wraps within TextBlock, ActualHeight is incorrect](https://stackoverflow.com/questions/15028455/when-text-wraps-within-textblock-actualheight-is-incorrect) – Rufus L Sep 12 '18 at 14:17
  • Try calling `UpdateLayout();` before accessing the `ActualHeight` property. – Rufus L Sep 12 '18 at 14:18

1 Answers1

0

Check this post: Determine WPF Textblock Height

The calculation might be like that:

private double GetHeight()
{
   double height = 0;
   foreach (var item in rootStackPanel.Children as IEnumerable)
   {
      if (item is TextBox tb)
      {
         tb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
         height += tb.DesiredSize.Height;
      }
   }
   return height;
}

Hope that helps.

Actually I have found one more post here.

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • Thanks for response. This is giving value but not accurate. If I put text in the text box (manually) then the actual height it is giving 90 of each textbox. But GetHeight in the code is giving 38 foreach textbox. – Kumar Sree Sep 12 '18 at 14:49
  • @Kumar Sree I don't see another related parts of your code. Just take into account, the ActualHeight property will 0 until a control is rendered. Therefore you should use Measure()+DesiredSize() to obtain TextBox sizes. – Jackdaw Sep 12 '18 at 15:13