views:

204

answers:

1

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

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

I have looked at Viewbox but can't see that it could work with wrappable text.

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

+1  A: 

What you're asking is more complex than it sounds, but I'll give you an idea:

<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>

And in code behind:

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();
}

Try it, drag it around, change the text...

Aviad P.
It works for (200,200), unfortunately it does not work for (440,330).If you try that constraint you'll notice the bottom line is clipped off. I have a screen shot and sample app if that helps.Any ideas?
ecard_guy
I'll reproduce it and update the post.
Aviad P.
Try now. Mind you this is just a lead, there's probably a better way to reach the optimal font size without incrementing it 1 by 1...
Aviad P.
With this last revision it seems to work perfectly for all cases - Thanks. It looks like working with the height only was the key. I'm now going to work on a custom control so it can easily be added to Xaml without changing the Window code behind. I have marked your answer correct.
ecard_guy
I'll be interested in getting that control when you're done with it, if there's no commercial considerations that is :)
Aviad P.
Not at all - I'll try to get it published with binary and source code to share for anyone who might find it use full -
ecard_guy
Still doesn't work - add this text to the sample above "problematic stuff". When narrowing the window the word "problematic" breaks into separate letters rather than downsizing the text. WPF cannot be tamed!
ecard_guy