How to use underline text on a label in WPF…

It was driving me nuts to do such a simple task as setting the font on the label to Underline in WPF. Well, its not that easy. You can’t just set the TextDecoration on the label since the label is a container control. Yes, you can set text to its Content property, but that just implicitly creates a TextBlock.

So, I wrote a quick helper function to let me set underlined text to any label.

Simple usage:

lblServer.Content = CreateUnderlinedTextBlock(  "Your Text Here" );

The actual function

        /// Creates the underlined text block.
        private TextBlock CreateUnderlinedTextBlock(string text)
            // Create an underline text decoration. Default is underline.
            TextDecoration myUnderline = new TextDecoration();

            // Create a linear gradient pen for the text decoration.
            Pen myPen = new Pen();           
            myUnderline.Pen  = new Pen(Brushes.Gray, 1);
            myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;

            // Set the underline decoration to a TextDecorationCollection and add it to the text block.
            TextDecorationCollection myCollection = new TextDecorationCollection();

            TextBlock blockHead = new TextBlock();
            blockHead.TextDecorations = myCollection;
            blockHead.Text = text;
            return blockHead;

I hope this helps!

Happy coding!

0 thoughts on “How to use underline text on a label in WPF…”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.