Search code examples
c#uwprichtextblock

RichTextBlock Styling in C#


I have a string in the format:

<strong>some text</strong> more text <strong> even more text </strong>

I would like to make the text surrounded by the strong tags bold in my richtextblock.

How would I go about doing this?


Solution

  • Here you go

    Xaml

    <RichTextBlock>
        <Paragraph>
            <Bold>Some Text</Bold> more text
            <Bold>Some other text</Bold>
        </Paragraph>
    </RichTextBlock>
    

    EDIT

    Presuming you have a Grid called LayoutGrid something like this should work

    C#

    var rtb = new RichTextBlock();
    var paragraph = new Paragraph();
    
    var bold1 = new Bold();
    bold1.Inlines.Add(new Run() { Text = "I am Bold" });
    paragraph.Inlines.Add(bold1);
    
    var normalText = new Run() { Text = " I am Normal" };
    paragraph.Inlines.Add(normalText);
    
    var bold2 = new Bold();
    bold2.Inlines.Add(new Run() { Text = " I am more Bold" });
    paragraph.Inlines.Add(bold2);
    
    rtb.Blocks.Add(paragraph);
    LayoutGrid.Children.Add(rtb); //Grid in your xaml