首页 > 解决方案 > 在 Xamarin 的 web 视图中将 CSS 样式表应用于 HTML 文档

问题描述

我有一个从 Xamarin WebView 中的服务器端呈现的 HTML 文档。我想将 CSS 样式表应用于 webview 中的 HTML 文档。

using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
        {
            using (Stream stream = httpResponse.GetResponseStream())
            {
                string response = (new StreamReader(stream)).ReadToEnd();
                ArticleData article = JsonConvert.DeserializeObject<ArticleData>(JsonConvert.DeserializeObject<ArticleDetails>(response).d);
                var htmlSource = new HtmlWebViewSource();
                htmlSource.Html = "<html><head><link rel='stylesheet' type='text/css' href='Assets/Main.css' /></head><body>" + article.Html + "</body></html>";
                webView.Source = htmlSource;
            }
        }

标签: xamarin.forms

解决方案


根据您的代码,css 在 Assets 中。由于我没有article.Html,我local.html在 Assets 文件夹中创建了一个供参考。

本地.html:

<html>
<head>
<title>webViewSample</title>
<link rel="stylesheet" type="text/css" href="Main.css" />
</head>
<body>
<h1>Xamarin.Forms</h1>
<p>This is a local Android Html page</p>
<img src="XamarinLogo.png" />
</body>
</html>

主.css:

html,body{margin:0;padding:10px}
body, p, h1 {
font-family: 'Roboto';
}

使用依赖服务从 Assets 文件夹中加载 CSS 和 html 文件。

[assembly: Xamarin.Forms.Dependency(typeof(BaseUrl_Android))]
namespace App27.Droid
{
public class BaseUrl_Android : IBaseUrl
{
    public string Get()
    {
        return "file:///android_asset/";
    }
}
}

xml:

<StackLayout>
   
    <Button Clicked="Button_Clicked"></Button>
    <WebView x:Name="webView"  HeightRequest="500"/>
</StackLayout>

后面的代码:

  public interface IBaseUrl { string Get(); }
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        var htmlSource = new HtmlWebViewSource();
        htmlSource.Html = "<html><head><link rel='stylesheet' type='text/css' href='Main.css' /></head><body>" + " <p><a href='local.html'>next page</a></p>" + "</body></html>";
        htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
        webView.Source = htmlSource;
    }
 }

截图:https ://imgur.com/My83Qvv


推荐阅读