【问题标题】:Insert Html file content in xamarin forms在 xamarin 表单中插入 Html 文件内容
【发布时间】:2020-01-04 13:05:15
【问题描述】:

我有一个 Html 文件。该 html 文件仅包含一些 div。我已经对所有 div 应用了一些样式,例如边距、颜色和字体系列。现在我想在我的 xamarin 表单应用程序中创建一个页面(在 ios 和 android 中),并希望在我的页面中添加该 html 文件的整个内容。

我尝试过使用 xamarin 表单的 Web 视图控件。但是我的 html 文件的内容太长了,因此,xamarin 代码也太长了,因为我们必须将 html 作为字符串应用到 web 视图控件。所以我不想用那种方式。

所以请给我简单的解释或解决方案以在 xamarin 表单中添加 html 文件。 希望有更好的解决方案。 提前致谢。

【问题讨论】:

标签: xamarin xamarin.forms xamarin.android xamarin.ios


【解决方案1】:

不是 100% 确定“xamarin 代码也会很长”是什么意思。

但是您可以在 ViewModelcode-behind 中创建 HtmlWebViewSource 对象,具体取决于您使用的方法,稍后您可以设置或绑定 WebViews 的 Source 属性。

为了从代码隐藏中设置它,您可以这样做:

var htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<html><body><h1>Xamarin is awesome</h1></body></html>";
yourWebView.Source = htmlSource;

另一方面,如果您使用 MVVM 和整个 View-ViewModel 概念,您只需要在您的 ViewModel 中拥有一个 HtmlWebViewSource 类型的属性,并在您的 View 中进行简单的绑定。

假设您有一个名为 HtmlSourceHtmlWebViewSource 类型的属性,您可以像我们在上一个示例中所做的那样将其值设置为您的 HTML 内容,而不是从 WebView 控件绑定到它,应该是这样的:

<WebView x:Name="yourWebView" Source="{Binding HtmlSource}"  WidthRequest="1000" HeightRequest="1000" />

希望这对您有所帮助,祝您编码顺利!

【讨论】:

    【解决方案2】:

    如果你想在你的 contentpage 中加载本地 html,我建议你可以使用 DependencyService 从 Android Assets 文件中获取 html url,我在 android 中创建了简单的,你可以看看。

    首先,在Android--Assets文件中创建html,命名为TestWebPage.html。

    然后在Form,IBaseUrl中创建接口。

    public interface IBaseUrl
    {
        string GetUrl();
    }
    

    然后在Android平台实现这个接口:

    public class LocalFiles : IBaseUrl
    {
        public string GetUrl()
        {
            return "file:///android_asset/";
        }
    }
    

    内容页面代码:

    <StackLayout>
        <!--  Place new controls here  -->
        <WebView
            x:Name="webviewjava"
            HeightRequest="300"
            WidthRequest="300" />
    </StackLayout>
    
    public MainPage()
        {
            InitializeComponent();
    
            var urlSource = new UrlWebViewSource();
    
            string baseUrl = DependencyService.Get<IBaseUrl>().GetUrl();
            string filePathUrl = Path.Combine(baseUrl, "TestWebPage.html");
            urlSource.Url = filePathUrl;
            webviewjava.Source = urlSource;
        }
    

    这里是github上的示例,大家可以看看:

    https://github.com/CherryBu/htmlapp

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多