【问题标题】:Loading an html asset that's stored within Xamarin.Forms into a webview将存储在 Xamarin.Forms 中的 html 资产加载到 web 视图中
【发布时间】:2018-11-27 13:15:24
【问题描述】:

我阅读了一个关于如何使用webview in Xamarin.Android 的现有问题,该问题建议在每个受支持的平台上编写特定于平台的代码。

理想情况下,我想将我的 html 存储在 Xamarin.Forms 中 /assets/ 内的文件中,而不是为每个操作系统存储一次。

我希望有一种更简单的方法,只需将资产存储在 Xamarin.Forms 中。这可能吗?

【问题讨论】:

  • 您是否面临与其他提问者相同的问题?
  • @G.hakim :不,另一个提问者想要一个适用于 Android 的解决方案 This only needs to be done through Android so there is no worries about about IOS and Windows. 我想降低多个操作系统的复杂性。
  • 那么您想要针对同一个问题的跨平台解决方案?
  • @G.hakim:是的。
  • 您能否分享一下您的 html 资产是如何存储的?它是作为对象还是作为文件?

标签: xamarin webview xamarin.forms


【解决方案1】:

我找到了让它工作的方法:

RightClickOnProject/Properties/Resources 中有一个视图允许添加可用作 Xamarin.Forms 中的资源的文件。我在那里添加了一个HtmlFile.txt-file。

我通过以下方式将 WebView 添加到 xaml

<ContentPage.Content>
    <StackLayout>
        <WebView x:Name="Web" VerticalOptions="FillAndExpand" />                     
    </StackLayout>
</ContentPage.Content>

然后在代码隐藏中我这样做:

public partial class OurPage: ContentPage
{
    public OurPage()
    {
        InitializeComponent();

        Web.Source = new HtmlWebViewSource{Html = Properties.Resources.HtmlFile};
    }
}

【讨论】:

    【解决方案2】:

    好吧,如果我是正确的,您可以使用资产文件夹中的嵌入式文件,然后使用System.IO 读取它(假设您使用的是 NET 标准程序集):

    • 将要读取的文件添加到可移植类的所需文件夹中,并确保 构建操作:EmbeddedResource

    • 然后使用 GetManifestResourceStream 使用其资源 ID 访问嵌入文件,默认情况下,资源 ID 是文件名,前缀为它所嵌入的项目的默认命名空间 - 在这种情况下,程序集是 WorkingWithFiles并且文件名是 PCLTextResource.txt,所以资源 ID 是 WorkingWithFiles.PCLTextResource.txt。现在要获取所需的文件数据,您只需要这样:

       var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
       Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLTextResource.txt");
       string text = "";
       using (var reader = new System.IO.StreamReader (stream)) {
       text = reader.ReadToEnd ();
       }
      

      LoadResourceText 是我在其中使用此代码获取当前程序集的 cs 文件。请注意,这应该与您刚刚添加的嵌入式资源所在的程序集相同,WorkingWithFiles.PCLTextResource.txt 是您的嵌入式资源的程序集路径,例如:如果您的程序集名称是 Foo 并且您的文件位于名为Asset 那么你的路径将类似于 Foo.Asset.Your_File.txt

    • 一旦你完成了这一切,那么简单的部分就开始了,在你的 WebView 页面中定义一个 HtmlWebViewSource 并将其分配给你的 WebView 和 Vola!你已经从你的文件中加载了数据。

          var browser = new WebView();
          var htmlSource = new HtmlWebViewSource();
          htmlSource.Html = ;//your html string here
          browser.Source = htmlSource;
      

    查看How to work with files了解更多信息。

    【讨论】:

    • LoadResourceText 需要导入什么?
    • 将其替换为您当前班级的名称,并确保这些图像与您当前班级的图像在同一个程序集中。
    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多