简体   繁体   English

WPF C#如何使用Text属性在TextBlock中设置格式化文本

[英]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. 我需要将后面的TextBlock代码的文本设置为包含格式化文本的字符串。

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 如果我以这种方式将此文本放在xaml文件中,则它可以正常工作

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

But if I set it using the Text property don't work. 但是,如果我使用Text属性设置它不起作用。

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. 但是问题是我从另一个来源获取了该字符串,却不知道如何将该字符串传递给TextBlock并查看其是否格式化。 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. 我希望有一种方法可以直接使用格式化的字符串设置TextBlock的内容,因为我不知道如何解析该字符串以将其与Inlines一起使用。

You may parse a TextBlock from your string and return a collection of its Inlines: 您可以从字符串中解析TextBlock并返回其内联的集合:

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中:

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

TextBlock wouldn't support that directly, you'd have write a method to parse the string yourself and set the styles on the inlines. TextBlock不直接支持该功能,您需要编写一个方法来自己解析字符串并设置内联样式。 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. 取决于您需要支持多少种样式,但是Regex是更简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM