How to make the text's fontsize auto fit its container?

Issue

In my Wpf prroject, a TextBlock is used to show app title. And to support multiple languages, the text is associated with a resource.

While the TextBlock’s parent UI container’s size is fixed. And for different language, the app title’s size might differ a lot.

In below code the font size of the Text is fixed to 20, that will cause UI problem when in some language. How to make the font size auto fit? Any idea?

<Border Grid.Row="0" Grid.ColumnSpan="2" BorderThickness="1" BorderBrush="{DynamicResource OCR.OCRWindow.TitleBorder}">
    <Grid Name="OCRTitleBar" Background="{DynamicResource OCR.OCRWindow.TitleBar}">
        <TextBlock Text="{x:Static prop:Resources.AppTitle}" FontSize="20" Foreground="White"
               HorizontalAlignment="Left" VerticalAlignment="Center" Margin="24,0,0,0"/>

Solution

Maybe wrapping the TextBlock inside a ViewBox scales the FontSize correctly

<Viewbox Stretch="Uniform">
       <TextBlock Text="{x:Static prop:Resources.AppTitle}" FontSize="20" Foreground="White" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="24,0,0,0"/>
</Viewbox>

There is a msdn article about setting up different stretch properties
How to: Apply Stretch Properties to the Contents of a Viewbox

Answered By – 0x30

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published