Search code examples
c#wpftextblock

Completely fill a TextBlock with repeating text


I need to create a textblock that is completely filled with a repeating text.

The font size should change as well so approximately the same number of characters are displayed no matter the textblock size.

I have the following code:

<TextBlock
    Name="Watermark"
    Background="White"
    FontSize="14"
    Foreground="DarkGray"
    TextWrapping="WrapWithOverflow" />

And the related code-behind:

// Really bad function...
void GenerateWatermarks()
{
    if (string.IsNullOrWhiteSpace(watermarkString))
    {
        return;
    }
    var builder = new StringBuilder();
    for(int i = 0; i < 50; i++)
    {
        builder.Append(watermarkString);
    }

    Watermark.Text = builder.ToString();
}

Here is an example of what I would like to get :

a busy cat

The text is generated in large quantity to fit the whole textblock, but if a resize occurs, the text nor the font size evolve


Solution

  • try placing TextBlock into a Viewbox with Stretch set to Fill or UniformToFill

    <Viewbox StretchDirection="Both" Stretch="Fill">
        <TextBlock
            Name="Watermark"
            Background="White"
            FontSize="14"
            Foreground="DarkGray"
            TextWrapping="WrapWithOverflow" 
            Width="480" Height="320"/>
    </Viewbox>
    

    enter image description here