WPF / XAML - Can text be automatic?

For a text area with a fixed wrap size, is there a way to make the font size as possible based on the amount of text?

For example, if you have an area of ​​500x500 with the text "Hello", the font size will be really large. But if you have a paragraph of text, the font size will be smaller to fit into the area.

I looked at the Viewbox, but I can’t see that it can work with wrappable text.

ANY xaml or code that could do this would help (it doesn't have to be a specific control).

+3
source share
1 answer

, , , , :

<DockPanel x:Name="LayoutRoot">
    <TextBox x:Name="text" Text="this is some text and some more text I don't see any problems..." DockPanel.Dock="Top" TextChanged="text_TextChanged"/>
    <TextBlock DockPanel.Dock="Top" Text="{Binding ElementName=tb, Path=FontSize}"/>
    <Border Name="bd" BorderBrush="Black" BorderThickness="1">
        <TextBlock Name="tb" Text="{Binding ElementName=text, Path=Text}" TextWrapping="Wrap"/>
    </Border>
</DockPanel>

:

public MainWindow()
{
    this.InitializeComponent();
    RecalcFontSize();
    tb.SizeChanged += new SizeChangedEventHandler(tb_SizeChanged);
}

void tb_SizeChanged(object sender, SizeChangedEventArgs e)
{
    RecalcFontSize();
}

private void RecalcFontSize()
{
    if (tb == null) return;
    Size constraint = new Size(tb.ActualWidth, tb.ActualHeight);
    tb.Measure(constraint);
    while (tb.DesiredSize.Height < tb.ActualHeight)
    {
        tb.FontSize += 1;
        tb.Measure(constraint);
    }
    tb.FontSize -= 1;
}

private void text_TextChanged(object sender, TextChangedEventArgs e)
{
    RecalcFontSize();
}

, , ...

+2

Source: https://habr.com/ru/post/1727080/


All Articles