NavigateToLocalStreamUri

如果 NavigateToString 无法处理某些内容,请使用 NavigateToLocalStreamUri 方法。它将强制 HTML 页面内的每个本地引用的 URI 调用特殊的解析器类,它可以动态提供正确的内容。

Assets / Html / html-sample.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML document</title>
    </head>
    <body>
        <p>This is simple HTML content.</p>
        <img src="cat.jpg"/>
    </body>
</html>

码:

protected override void OnNavigatedTo(NavigationEventArgs args)
{
    // The Uri resolver takes is in the form of "ms-local-stream://appname_KEY/folder/file"
    // For simplicity, there is method BuildLocalStreamUri which returns correct Uri.
    var uri = this.webView.BuildLocalStreamUri("SomeTag", "/html-sample.html");
    var resolver = new StreamUriResolver();
    this.webView.NavigateToLocalStreamUri(uri, resolver);

    base.OnNavigatedTo(args);
}

public sealed class StreamUriResolver : IUriToStreamResolver
{
    public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
    {
        if (uri == null)
        {
            throw new ArgumentNullException(nameof(uri));
        }

        var path = uri.AbsolutePath;

        return GetContent(path).AsAsyncOperation();
    }

    private async Task<IInputStream> GetContent(string uriPath)
    {
        Uri localUri;

        if (Path.GetExtension(uriPath).Equals(".html"))
        {
            localUri = new Uri("ms-appx:///Assets/Html" + uriPath);
        }
        else
        {
            localUri = new Uri("ms-appdata:///local/content" + uriPath);
        }

        var file = await StorageFile.GetFileFromApplicationUriAsync(localUri);
        var stream = await file.OpenAsync(FileAccessMode.Read);

        return stream.GetInputStreamAt(0);
    }
}

此代码将从应用程序包中获取 HTML 页面,并将本地文件夹中的内容嵌入其中。如果你在/ local / content 文件夹中有图像“cat.jpg”,它将显示带有猫图像的 HTML 页面。