基本上有两种方法。
1]您可以使用Label 的Span 属性在Label 中输入格式化文本,就像:
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="This is a " FontSize="15" TextColor="Blue"/>
<Span Text="Rich Text" FontSize="30" TextColor="Red"/>
<Span Text=" inside a Label in Xamarin Forms" FontSize="15" TextColor="Blue" />
</FormattedString>
</Label.FormattedText>
</Label>
您还可以在Span 中使用Binding 以及在Span 中使用Label 的所有样式和其他属性。
2] 第二种方法是,使用Label 的TextType 属性并将其设置为TextType="Html"。但请注意,Label TextType="Html" 根据应用运行的底层平台限制了支持的 HTML 标签。
我们可以在 C# 代码后面或直接在 XAML 中定义 HTML。
内部 C# 代码:
Label richTextLabel = new Label
{
Text = "This is <strong style=\"color:red\">HTML</strong> text.",
TextType = TextType.Html
};
// OR
richTextLabel.Text = "This is <strong style=\"color:red\">HTML</strong> text."
richTextLabel.TextType = TextType.Html;
// In XAML set Label Name as <Label x:Name="richTextLabel" />
在 XAML 中
<Label Text="This is <strong style="color:red">HTML</strong> text."
TextType="Html" />
<!--The symbols <, >, " needs to be escaped -->
RE: Refer this for more documentation.
结论:
使用Span 的第一种方法非常可靠,因为所有内容都将按编码呈现。
第二种方式,不同底层平台的Label不支持大部分HTML标记。
因此推荐第一种方法。