1

i try to calculate the height of TextBlock. I dont want to take the Textblock on some page. I just have to know the height of my Content.

I tried it this way, but it just returns 0

private static double CalculateContentHeight(string content, double width, double fontSize)
{
    //Nur einen Textblock ggf. um Ressourcen zu sparen
    TextBlock textblock = new TextBlock
    {
        FontSize = fontSize,
        Text = content,
        TextWrapping = TextWrapping.Wrap,
        MaxWidth = width,
        Height = Double.NaN

    };
    return textblock.ActualHeight;
}

If i take a existing TextBlock in XAML and just:

MyXAMLTextBlock.MaxWidth = 7;
double height = MyXAMLTextBlock.ActualHeight;

I get the right value for it.

I know there are possibilitys with Meassure() and Arrange() like in this Example, but Meassure(Size) takes the size paramter and i dont have the height for it.

I know that you can set the size on Auto with Double.Nan, but it doesnt compile with

double height = 9;
Size s = new Size(height, Double.Nan);

Maybe you can help me and thanks a lot.

Community
  • 1
  • 1
Peter
  • 1,655
  • 22
  • 44

1 Answers1

5

I have no idea why you are doing this. But with Measure and Arrange it is possible:

Just run this two lines before you return the ActualHeight:

textblock.Measure(new Size());
textblock.Arrange(new Rect());

Hope I could help you

Claudio P
  • 2,133
  • 3
  • 25
  • 45
  • Thank you! I will try this tomorrow. I need it to calculate a table withou creating it, because it takes to much memory. – Peter Aug 04 '14 at 13:31
  • Use Windows.Foundation and this sets the Actual Height/Width – 27k1 Nov 01 '20 at 16:35