【问题标题】:How to add Rich Text or HTML in Label or Text field in Xamarin Forms?如何在 Xamarin Forms 的标签或文本字段中添加富文本或 HTML?
【发布时间】:2020-05-31 22:28:58
【问题描述】:

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

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

【问题讨论】:

    标签: xaml xamarin xamarin.forms


    【解决方案1】:

    基本上有两种方法。

    1]您可以使用LabelSpan 属性在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] 第二种方法是,使用LabelTextType 属性并将其设置为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 &lt;strong style=&quot;color:red&quot;&gt;HTML&lt;/strong&gt; text."
           TextType="Html"  />
    
    <!--The symbols <, >, " needs to be escaped -->
    

    RE: Refer this for more documentation.

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

    【讨论】:

      猜你喜欢
      • 2022-09-02
      • 2012-03-25
      • 2020-03-14
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多