我想在 Xamarin 窗体项目Label
或任何文本字段中添加富文本或格式化文本。我尝试为文本使用单独的标签,也使用WebView
等。但他们都没有奏效。使用Webview
以某种方式工作,但每次更改内容时都需要刷新。将 AJAX 与WebView
一起使用需要 Web 服务器,因此它无法在本地/脱机工作。
我只想在只读模式下Label
上添加富文本,或者可以在运行时从隐藏的代码进行修改。
基本上有两种方法可以做到这一点。
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# 代码中定义 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 <strong style="color:red">HTML</strong> text."
TextType="Html" />
<!--The symbols <, >, " needs to be escaped -->
回复:有关更多文档,请参阅此内容。
结论:使用Span
的第一种方法非常可靠,因为所有内容都将按编码呈现。 在第二种方法中,不同基础平台中的Label
不支持大多数 HTML 标记。 因此,建议使用第一种方法。