Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change font size if the text exceeds the boundary of Textblock

Tags:

c#

.net

wpf

xaml

I have a textblock with a dimension of Width=511, Height=159. FontSize=28. I want to change the font size if the text exceeds the dimension of the textblock so that all the text will be displayed. Is there a way of doing this? A formula maybe?

like image 574
patlimosnero Avatar asked Aug 18 '11 13:08

patlimosnero


1 Answers

This solution implies the use of a ViewBox, i think that with Wpf transforming features there is no need to change the font size of the text, Almost the same result can be archieved using transformation (and a ViewBox in this case).

Instead of putting your TextBlock inside a ViewBox, modify it's template and put the control where the text appears inside a ViewBox, something like:

<ControlTemplate TargetType="{x:Type TextBox}">                     
    <Microsoft_Windows_Themes:ListBoxChrome x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" SnapsToDevicePixels="true">
        <Viewbox HorizontalAlignment="Left">
            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Viewbox>
    </Microsoft_Windows_Themes:ListBoxChrome>

    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Now you get a control that sizes it's text to fit in the available spacee, thanks WPF.

Also here is some example

text example

like image 77
Ariel Avatar answered Oct 21 '22 08:10

Ariel