Setting FontSize programmatically

I was moving a WinForms app to WPF and I was perplexed for quite a while this morning when I found that setting the FontSize on a WPF TextBlock didn’t really give me the font-size I expected (the one that WinForms gave me). It was obvious pretty soon that WinForms was using point as the unit while the WPF default was to use device independent pixels. For a while I was confused as to how to set the font-size in points programmatically, since the FontSize setter only took a double and thus I couldn’t pass a unit-specific string as I could in Xaml. The solution was simple and it beats me why I didn’t think of it sooner, but for those others who occasionally hit dense brain periods like I do, the trick is to use FontSizeConverter.

double pointSize = (double)new FontSizeConverter().ConvertFrom("8pt");
Advertisements

2 thoughts on “Setting FontSize programmatically

  1. Thank you so much for this. I can’t tell you how many hours I have spent searching for the answer to this problem. Why isn’t FontSizeConverter() at the top of every search I have done?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s