Search code examples
wpfxamlstyles

WPF - TextBlock - Format Text Programmatically


In the TextBlock object you can format the text in the XAML like this:

<TextBlock>
    <Bold>bold text</Bold> random non bold next
</TextBlock>

How do you do the "Bold" tags programmatically?

I tried just putting them in the text property and it just printed them out (the tags were printed as text).


Solution

  • Visual Basic Version:

    Dim tb As New TextBlock
    
    Dim b As New Bold
    b.Inlines.Add(New Run("bold text"))
    
    tb.Inlines.Add(b)
    tb.Inlines.Add(New Run("random non bold text"))
    

    C# Version:

    TextBlock tb = new TextBlock();
    var bold = new Bold(new Run("Bold Text"));
    tb.Inlines.Add(bold);
    
    var normal = new Run("Normal Text"));
    tb.Inlines.Add(normal);