如何在 Xamarin 窗体的标签或文本字段中添加富文本或 HTML?



我想在 Xamarin 窗体项目Label或任何文本字段中添加富文本格式化文本。我尝试为文本使用单独的标签,也使用WebView等。但他们都没有奏效。使用Webview以某种方式工作,但每次更改内容时都需要刷新。将 AJAX 与WebView一起使用需要 Web 服务器,因此它无法在本地/脱机工作。

我只想在只读模式下Label上添加富文本,或者可以在运行时从隐藏的代码进行修改。

基本上有两种方法可以做到这一点。

1]您可以使用Label的属性SpanLabel中输入格式化文本 就像:

<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]第二种方法是,使用LabelTextType属性并将其设置为TextType="Html"。但请注意,根据运行应用程序的底层平台,Label TextType="Html"支持的 HTML 标记有限。

我们可以在 C# 代码中定义 HTML,也可以直接在 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 &lt;strong style=&quot;color:red&quot;&gt;HTML&lt;/strong&gt; text."
TextType="Html"  />
<!--The symbols <, >, " needs to be escaped -->

回复:有关更多文档,请参阅此内容。

结论:使用Span的第一种方法非常可靠,因为所有内容都将按编码呈现。 在第二种方法中,不同基础平台中的Label不支持大多数 HTML 标记。 因此,建议使用第一种方法。

最新更新