Using a System.Drawing.Font with a WPF Label

bstoney picture bstoney · Mar 12, 2009 · Viewed 16.2k times · Source

I have a WPF Label control which I'm trying to change the appearance of using a System.Drawing.Font object supplied by some legacy code. I have been able to set most of the properties, but am struggling with Strikeout and Underline.

So far I have:

System.Drawing.Font font = FontFromLegacyCode();

System.Windows.Controls.Label label = new System.Windows.Controls.Label();
label.FontFamily = new System.Windows.Media.FontFamily( font.Name );
label.FontWeight = font.Bold ? System.Windows.FontWeights.Bold : System.Windows.FontWeights.Regular;
label.FontStyle = font.Italic ? System.Windows.FontStyles.Italic : System.Windows.FontStyles.Normal;
label.FontSize = font.Size;

How do you set the font strikeout or underline properties? Is there a better control to use?

Answer

Ray picture Ray · Mar 12, 2009

I would change it to a TextBlock control. The TextBlock control has the TextDecorations property you can use.

<TextBlock Name="textBlock" TextDecorations="Underline, Strikethrough" />

Or you can stick a TextBlock inside a Label if you really like (although I'd just use the TextBlock by itself).

<Label Name="label">
    <TextBlock Name="textBlock" TextDecorations="Underline, Strikethrough" />
</Label>

Have a look at the TextDecorations class.

I find that TextBlocks are more suitable than Labels in most situations. Here's a blog post about the differences. The chief difference being that a Label is a Control whereas a TextBlock is just a FrameworkElement. Also a Label supports access keys.