Monday, October 27, 2008

MSDN Question on WPF: How to decrease font-size automatically so that it fits completely inside a label?

Problem
I came across an interesting question on WPF forums. A user has a fixed size label which text can be very large. But since the size of the label is fixed, the text gets truncated which he does not want. The user wanted to automatically decrease the font-size such that it fits into the label completely.
Solution
One solution is to write some code to determine the available space and based on the space available use FormattedText and set the text dynamically. But I devised an easier solution.
There is a container in WPF called ViewBox which automatically scales the content inside such that it fits into the space completely. The idea is to use this ViewBox inside the template of the Label. The XAML code that does this is shown.

<Label Width="200" Height="300" Content="This is a very long text that you would be using to set the control text">
<
Label.Template>
<
ControlTemplate>
<
Viewbox>
<
ContentPresenter
Content="{TemplateBinding Property=ContentControl.Content}" />
</
Viewbox>
</
ControlTemplate>
</
Label.Template>
</
Label>

Now, when you run an application hosting such a label, the screenshots are shown.


image


The same application with much longer text is shown below.


image 
Hope this would be helpful to many!

No comments: