WPF C# 如何使用 Text 属性在 TextBlock 中设置格式化文本
我需要将 TextBlock 代码后面的文本设置为包含格式化文本的字符串.
I need to set the text of a TextBlock code behind to a string containing formatted text.
例如这个字符串:
"This is a <Bold>message</Bold> with bold formatted text"
如果我以这种方式将此文本放入 xaml 文件中,它就可以正常工作
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>
但如果我使用 Text 属性设置它不起作用.
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");
但问题是我从另一个来源获取字符串,我不知道如何将此字符串传递给 TextBlock 并查看是否已格式化.我希望有一种方法可以直接使用格式化字符串设置 TextBlock 的内容,因为我不知道如何解析字符串以将其与 Inlines 一起使用.
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.
您可以从字符串中解析 TextBlock 并返回其内联的集合:
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
}
然后将集合添加到您的 TextBlock:
Then add the collection to your TextBlock:
textBlock.Inlines.AddRange(
ParseInlines("This is a <Bold>message</Bold> with bold formatted text"));