Search code examples
c#wpftextblockunderline

Is there a way to underline one character in a WPF TextBlock?


Is there a way to apply an underline text decoration to one character only in a TextBlock (or any amount less than the full block)?

I have some text that I want output as "this worf is misspelt" and have the f in worf underlined.

I know you can do:

TextBlock47.TextDecorations = TextDecorations.Underline;

but I don't want the entire block underlined.

Failing that, is there another control I can use other than TextBlock that gives this capability? I've looked into rich text but that seems like an awful lot of work for what's a simple effect. If that is the only way, how do I go about generating text of a specific format (10pt, Courier New, one character underlined) in c# code?


Solution

  • You can use Underline in a TextBlock:

    <TextBlock Name="textBlock47">
      this wor<Underline>f</Underline> is misspelt
    </TextBlock>
    

    or

    textBlock47.Inlines.Add(new Run("this wor"));
    textBlock47.Inlines.Add(new Underline(new Run("f")));
    textBlock47.Inlines.Add(new Run(" is misspelt"));