Formatting text in a TextBlock

前端 未结 6 2122
青春惊慌失措
青春惊慌失措 2020-11-27 11:58

How do I achieve formatting of a text inside a TextBlock control in my WPF application?

e.g.: I would like to have certain words in bold, others in ital

6条回答
  •  独厮守ぢ
    2020-11-27 12:05

    There are various Inline elements that can help you, for the simplest formatting options you can use Bold, Italic and Underline:

    
        Sample text with bold, italic and underlined words.
    
    

    enter image description here

    I think it is worth noting, that those elements are in fact just shorthands for Span elements with various properties set (i.e.: for Bold, the FontWeight property is set to FontWeights.Bold).

    This brings us to our next option: the aforementioned Span element.

    You can achieve the same effects with this element as above, but you are granted even more possibilities; you can set (among others) the Foreground or the Background properties:

    
        Sample text with bold, italic and underlined words. Coloring is also possible.
    
    

    enter image description here

    The Span element may also contain other elements like this:

    
        Italic text with some coloring.
    
    

    enter image description here

    There is another element, which is quite similar to Span, it is called Run. The Run cannot contain other inline elements while the Span can, but you can easily bind a variable to the Run's Text property:

    
        Username: 
    
    

    enter image description here

    Also, you can do the whole formatting from code-behind if you prefer:

    TextBlock tb = new TextBlock();
    tb.Inlines.Add("Sample text with ");
    tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
    tb.Inlines.Add(", ");
    tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
    tb.Inlines.Add("and ");
    tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
    tb.Inlines.Add("words.");
    

提交回复
热议问题