Search code examples
c#wpftextblock

WPF C# How to set formatted text in TextBlock using Text property


I need to set the text of a TextBlock code behind to a string containing formatted text.

For example this string:

"This is a <Bold>message</Bold> with bold formatted text"

If I put this text in xaml file in this way it work correctly

<TextBlock>
  This is a <Bold>message</Bold> with bold formatted text
</TextBlock>

But if I set it using the Text property don't work.

string myString = "This is a <Bold>message</Bold> with bold formatted text";
myTextBlock.Text = myString;

I know I can use Inlines:

myTextBlock.Inlines.Add("This is a");
myTextBlock.Inlines.Add(new Run("message") { FontWeight = FontWeights.Bold });
myTextBlock.Inlines.Add("with bold formatted text");

But the problem is that I get the string as it is from another source and I have no idea how I can pass this string to the TextBlock and see if formatted. I hope there is a way to set the content of the TextBlock directly with the formatted string, because I have no idea of how I can parse the string to use it with Inlines.


Solution

  • You may parse a TextBlock from your string and return a collection of its Inlines:

    private IEnumerable<Inline> ParseInlines(string text)
    {
        var textBlock = (TextBlock)XamlReader.Parse(
            "<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"
            + text
            + "</TextBlock>");
    
        return textBlock.Inlines.ToList(); // must be enumerated
    }
    

    Then add the collection to your TextBlock:

    textBlock.Inlines.AddRange(
        ParseInlines("This is a <Bold>message</Bold> with bold formatted text"));