有各种Inline 元素可以帮助您,对于最简单的格式化选项,您可以使用Bold、Italic 和Underline:
<TextBlock>
Sample text with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> words.
</TextBlock>
我认为值得注意的是,这些元素实际上只是具有各种属性集的Span 元素的简写(即:对于Bold,FontWeight 属性设置为FontWeights.Bold)。
这给我们带来了下一个选项:前面提到的Span 元素。
你可以用这个元素达到和上面一样的效果,但你被赋予了更多的可能性;您可以设置(除其他外)Foreground 或 Background 属性:
<TextBlock>
Sample text with <Span FontWeight="Bold">bold</Span>, <Span FontStyle="Italic">italic</Span> and <Span TextDecorations="Underline">underlined</Span> words. <Span Foreground="Blue">Coloring</Span> <Span Foreground="Red">is</Span> <Span Background="Cyan">also</Span> <Span Foreground="Silver">possible</Span>.
</TextBlock>
Span 元素还可以包含其他元素,如下所示:
<TextBlock>
<Span FontStyle="Italic">Italic <Span Background="Yellow">text</Span> with some <Span Foreground="Blue">coloring</Span>.</Span>
</TextBlock>
还有一个元素,和Span很相似,叫做Run。 Run 不能包含其他内联元素,而 Span 可以,但您可以轻松地将变量绑定到 Run 的 Text 属性:
<TextBlock>
Username: <Run FontWeight="Bold" Text="{Binding UserName}"/>
</TextBlock>
此外,如果您愿意,您可以从代码隐藏中进行整个格式化:
TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");