user2272143
user2272143

Reputation: 469

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.

Upvotes: 3

Views: 4745

Answers (2)

Clemens
Clemens

Reputation: 128146

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"));

Upvotes: 5

SledgeHammer
SledgeHammer

Reputation: 7736

TextBlock wouldn't support that directly, you'd have write a method to parse the string yourself and set the styles on the inlines. Doesn't look that difficult to parse. Use regular expressions or a token parser. Depends on how many different styles you need to support, but Regex is the easier approach.

Upvotes: 1

Related Questions