如何在 xamarin 表单中显示 html 格式的文本

How can I show text with html format in xamarin forms

我使用 json 处理网络服务,我得到 html 格式的文本。我希望我的文本具有超链接和我从 html 标签(等。粗体)中找到的一些其他属性。

我尝试在 WebView 源中绑定我的 html 字符串,但 WebView 每次都是空白的。我用这个代码

var browser = new WebView();
var htmlSource = new HTMLWebViewSource();
htmlSource.Html = MyItem.Article;
browser.Source = htmlSource;

MyItem.Article字符串是这样的

我想要在 ListView 中的 Label 中有这样的东西 os 像这样的东西。

我该怎么做?

这应该适合你

string htmlText = MyItem.Article.ToString().Replace(@"\", string.Empty);
var browser = new WebView ();
var html = new HtmlWebViewSource {
  Html = htmlText
};
browser.Source = html;

因为Xamarin.Forms.HtmlWebViewSource.HTML期待一个纯粹的HTML。使用它,您可以在本文 http://blog.falafel.com/creating-reusable-xaml-user-controls-xamarin-forms/ 干杯的帮助下创建 Xamarin.Forms 用户控件

仅供参考,我刚刚在我的 Forms9Patch library 中添加了创建标签和按钮的功能,您可以在其中通过 HTML 设置文本格式。例如:

new Forms9Patch.Label { HtmlText =  "plain <b><i>Bold+Italic</i></b> plain"}

... 会给你一个标签,其中文本在字符串中间被格式化为粗体斜体。

另外,顺便说一句,它允许您使用自定义字体,这些字体是您 PCL 项目中嵌入的资源,无需任何特定于平台的工作。而且,您可以通过 HTLM <font> 标签或 HTML font-family 属性使用这些字体。

以下是 demo app:

的一些屏幕截图

在 XAML 中你可以这样做:

<WebView>
   <WebView.Source>
      <HtmlWebViewSource Html="{Binding HtmlText}"/>
   </WebView.Source>
</WebView>

如果 WebView 不在 Grid 内,您可能还需要提供 WebView 的高度和宽度。

<pre>
    <WebView VerticalOptions="FillAndExpand">
         <WebView.Source>
              <HtmlWebViewSource Html="{Binding HtmlText}"/>
         </WebView.Source>
    </WebView>
</pre>