WPF TextBlock font resize to fill available space in a Grid

I have some text that is displayed at run time in a textblock. I want the font size to be the biggest it can be to fill the area that is given. I think I have the textblock setup correctly to "autosize" and I try to increase the font size till the textblock is bigger than than its parent then decrease the font size by 1. The problem is I can't get the control to redraw/recompute its size.

Is the a better way to do that? Or is there a way I can make my method work?


Wrap the TextBlock inside a ViewBox:

   <Grid>
    <Viewbox>
        <TextBlock TextWrapping="Wrap" Text="Some Text" />
    </Viewbox>
   </Grid>

I had the same problem. You can use this to resize the fontsize of the textblock to fill the area when it has overflow.


<Viewbox StretchDirection="DownOnly" Stretch="Uniform">
    <TextBlock Text="{Binding Path=Title}" HorizontalAlignment="Center"/>
</Viewbox>


The WPF ViewBox control can grow / shrink with its contents to the available space.

Just place your TextBlock within a ViewBox as;

<Viewbox Stretch="Uniform" Width="50" Height="50">
    <TextBlock Text="Test" />
</Viewbox>

ViewBox is typically scaled by its container.


I found a great way to do this using ViewBox:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="50" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>
    <Viewbox Grid.Row="0" Grid.Column="0" Stretch="Uniform">
        <TextBlock Name="tbTest" Background="Yellow" Text="This is some text" />    
    </Viewbox>

    <ContentControl Grid.Column="0" Grid.Row="2">
        <TextBlock>This is some text</TextBlock>
    </ContentControl>
</Grid>

Well, its not a "perfect" answer, but this is a quick hack (you can drop this into kaxaml and test it out):

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid Height="300" Background="green">  
  <Viewbox>
  <TextBlock Background="red" Text="Hurr"/>
  </Viewbox>
  </Grid>
</Page>

The ViewBox will enlarge any content to fill its container. The problem is that the TextBlock, while it sizes to its text, has padding at the top and bottom that you can't get rid of (without doing some heavy lifting). This might get you closer to what you want, tho.