0

i need to set height of UiElement based on the content . i set content to a text block and set text block MaxWidth is some value and MaxHeight is double.MaxValue. now i set this textblock to child of border.nowi measure the border like below

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;

but above code give the incorrect desiredsize for different width of text block. is there any other way to calculate the height based on text content.

SharpGobi
  • 144
  • 1
  • 13

3 Answers3

0

Use the following

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

It will adapt the TextBlock Size to have always a Rectangle of that Width.

Try and tell me if it the solution for your case

Juan Pablo Garcia Coello
  • 3,192
  • 1
  • 23
  • 33
0

I think you're actually looking for the WCF Control called StackPanel, but I'll provide the code to change height programatically aswell.

Using StackPanel, in 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>

Or to change TextBlock height programatically:

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

And then your code is simply: border.Height = textBlock.Height;

NLindbom
  • 498
  • 6
  • 12
0
 <Border Width="300" BorderThickness="1" BorderBrush="Black">
    <TextBlock Text="welcome" Foreground="Blue"/>
    </Border>
Jayasri
  • 237
  • 1
  • 11