3
votes

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.

2
It looks like your trying to copy formatted text from another application (Microsoft Word?) and paste it into your TextBlock, is that a correct assumption?hcham1
I get this string from another application but I don't get it by copy/past but from TCP connectionuser2272143
How is the string formatted when you receive it? Will it look just like "This is a <Bold>message</Bold> with bold formatted text"hcham1
As in my exampleuser2272143
I can also get the string in different formats. ie. <Bold></Bold> or <b></b>. I donìt know how thi can be useful but it give me this option.user2272143

2 Answers

4
votes

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

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.