C# 如何根据文本块中的内容设置UIElement的动态高度

C# 如何根据文本块中的内容设置UIElement的动态高度,c#,wpf,xaml,wpf-controls,uielement,C#,Wpf,Xaml,Wpf Controls,Uielement,我需要根据内容设置UiElement的高度。我将内容设置为文本块,并将文本块MaxWidth设置为某个值,MaxHeight设置为double.MaxValue。现在我将这个textblock设置为border的子级。现在我测量边框,如下所示 textBlock.MaxWidth=200; textBlock.MaxHeight=double.MaxValue; var area=new Border{child=textBlock}; area.Measure(new size(textBlo

我需要根据内容设置UiElement的高度。我将内容设置为文本块,并将文本块MaxWidth设置为某个值,MaxHeight设置为double.MaxValue。现在我将这个textblock设置为border的子级。现在我测量边框,如下所示

textBlock.MaxWidth=200;
textBlock.MaxHeight=double.MaxValue;
var area=new Border{child=textBlock};
area.Measure(new size(textBlock.MaxWidth,textBlock.MaxHeight));
var r=area.DesiredSize;
但是上面的代码对于不同宽度的文本块给出了不正确的期望大小。是否有其他方法根据文本内容计算高度。

使用以下方法

<ViewBox Width="200">
 <TexBlock Text="..." ... />
</ViewBox>

它将调整文本块大小,使其始终具有该宽度的矩形


试着告诉我它是否是您案例的解决方案

我认为您实际上在寻找名为StackPanel的WCF控件,但我也会提供代码以编程方式更改高度

使用StackPanel,以XAML为单位:

<StackPanel Width="200">
    <Border BorderThickness="1" BorderBrush="Black">
        <TextBlock TextWrapping="Wrap" Text="This TextBlock will be 
            wrapped by a black Border that has the height of the TextBlock
            and with it's Width provided from the StackPanel"/>
    </Border>
</StackPanel>

或以编程方式更改文本块高度:

<Border x:Name="border" BorderBrush="Black" BorderThickness="1" Height="100" Width="200">
    <TextBlock x:Name="textBlock" Background="Black" Width="40" Height="40"/>
</Border>

然后您的代码就是:
border.Height=textBlock.Height


 <Border Width="300" BorderThickness="1" BorderBrush="Black">
    <TextBlock Text="welcome" Foreground="Blue"/>
    </Border>