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

use*_*143 3 c# wpf textblock

我需要将 TextBlock 代码后面的文本设置为包含格式化文本的字符串。

例如这个字符串:

"This is a <Bold>message</Bold> with bold formatted text"
Run Code Online (Sandbox Code Playgroud)

如果我以这种方式将此文本放入 xaml 文件中,它可以正常工作

<TextBlock>
  This is a <Bold>message</Bold> with bold formatted text
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

但如果我使用 Text 属性设置它,则不起作用。

string myString = "This is a <Bold>message</Bold> with bold formatted text";
myTextBlock.Text = myString;
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用内联:

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

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

Cle*_*ens 5

您可以从字符串中解析 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
}
Run Code Online (Sandbox Code Playgroud)

然后将集合添加到您的 TextBlock 中:

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