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

Jun*_*min 1 xaml xamarin xamarin.forms

我想在 Xamarin Forms 项目中或任何文本字段中添加富文本格式化文本Label。我曾尝试为文本使用单独的标签,也尝试使用WebView等。但它们都不起作用。使用 aWebview以某种方式工作,但每次更改内容时都需要刷新。使用 AJAXWebView需要一个 Web 服务器,因此它不能在本地/离线工作。

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

Jun*_*min 5

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

1]您可以使用a的Span属性在Label里面输入格式化文本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>
Run Code Online (Sandbox Code Playgroud)

您还可以使用BindinginSpanLabelinside 的每个样式和其他属性Span


2]第二种方法是,使用的TextType属性Label并将其设置为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" />
Run Code Online (Sandbox Code Playgroud)

在 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 -->
Run Code Online (Sandbox Code Playgroud)

RE:有关更多文档,请参阅此处。

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