Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you have Silverlight resize text content to fit?

I've got a user control (below), I'm binding the text to a datasource and instancing up a bunch of the usercontrols.

I want the size of the text to be the largest possible that will still fit in the bounds of the control. In Windows programming, I could measure the text size decrementing the font size until it fit the target dimensions.

Is there any way of doing this in Silverlight?

I know I could presumably do it in a similar way, but are there any 'nicer' ways of doing it?

<Grid x:Name="gdBubble" Width="180" Height="95">
    <Ellipse x:Name="elBubble" Fill="#FFFFA300" />
    <TextBlock x:Name="txtContent" Text="{ Binding ClientName }" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

[I'm using a grid here in order for the textblock to center correctly.]

The answer was as Rich described to use a Viewbox.

This was the winning configuration (for me):

<Grid x:Name="gdBubble" Width="180" Height="95">
    <Ellipse x:Name="elBubble" Fill="#FFFFA300" />
    <controls:Viewbox Margin="10,10,10,10" VerticalAlignment="Stretch" Height="Auto">
        <TextBlock x:Name="txtContent" FontSize="18" Text="{ Binding ClientName }" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </controls:Viewbox>
</Grid>
like image 275
Tristan Warner-Smith Avatar asked Apr 09 '09 15:04

Tristan Warner-Smith


1 Answers

A similar question was asked yesterday about resizing content automatically relative to the size of a container. The answer in this case is the same: use a Viewbox. If you put your TextBlock inside of the Viewbox, the TextBlock will resize itself to only use the space it needs, and the Viewbox will handle stretching this to the dimensions of the container. Use the stretch attribute to choose from one of four stretching methods.

Take a look at this thread from yesterday:

WPF Gui that changes size with window?

like image 182
Rich Avatar answered Sep 28 '22 03:09

Rich