查找文本块/文本的高度

Pet*_*ter 1 c# xaml windows-store-apps

我尝试计算TextBlock的高度。我不想在某些页面上使用 Textblock。我只需要知道我的内容的高度。

我这样试过,但它只返回 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;
}
Run Code Online (Sandbox Code Playgroud)

如果我在 XAML 中使用现有的 TextBlock 并且只是:

MyXAMLTextBlock.MaxWidth = 7;
double height = MyXAMLTextBlock.ActualHeight;
Run Code Online (Sandbox Code Playgroud)

我得到了正确的价值。

我知道 Meassure() 和 Arrange() 有可能像在这个例子中一样,但是 Meassure(Size) 需要大小参数,我没有它的高度。

我知道你可以用 Double.Nan 在 Auto 上设置大小,但它不能编译

double height = 9;
Size s = new Size(height, Double.Nan);
Run Code Online (Sandbox Code Playgroud)

也许你可以帮助我,非常感谢。

Cla*_*o P 5

我不知道你为什么要这样做。但是使用 Measure 和Arrange 是可能的:

在返回 ActualHeight 之前运行这两行:

textblock.Measure(new Size());
textblock.Arrange(new Rect());
Run Code Online (Sandbox Code Playgroud)

希望我能帮到你