K Mehta
K Mehta

Reputation: 10533

Dynamic TextBlock font size in Silverlight

I am currently wrapping my TextBlock in a Viewbox as suggested by a couple of answers here on StackOverflow, and this renders as I want it to. But after doing a little research, I understand that this hampers performance, especially when you have a decent number of TextBlocks which use this approach.

Is there a better way of doing this in Silverlight?

Note: I don't mind using something other than a TextBlock as long as I can display text.

Upvotes: 3

Views: 2132

Answers (1)

Emond
Emond

Reputation: 50672

From this forum

// Event handler
private void ControlsSizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
{
    GetFontSize(sender as Control);
}

// Method for font size changes
public static void GetFontSize(Control control)
{
    PropertyInfo info;
    if (control == null || control.ActualHeight <= 0)
        return;
    if(( info = control.GetType().GetProperty("FontSize", typeof(double))) != null)
    {
        info.SetValue(control, 0.7 * control.ActualHeight, null);
    }
}

No ViewBoxes involved just a magic calculation. There are other suggestions in the thread such as changing the font size and measuring a couple of times until the text fits.

Upvotes: 1

Related Questions