UWP Xamarin.Forms 和 Windows Phone 8.1 中的 Webview BaseURL

Webview BaseURL in Xamarin.Forms on UWP and Windows Phone 8.1

在我共享的便携式 Xamarin 项目中,这适用于 UWP,Windows Phone 8.1 和 Windows 8.1:

HtmlWebViewSource htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<html><body><img src='ms-appx-web:///Assets/somePicture.png' /></body></html>";
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
WebView webView = new WebView
{
        Source = htmlSource,
};

显然,这不是跨平台的(iOS 和 Android)。我想要这个,但它不适用于 UWP,Windows Phone 8.1 和 Windows 8.1:

HtmlWebViewSource htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<html><body><img src='somePicture.png' /></body></html>";
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
WebView webView = new WebView
{
        Source = htmlSource,
};

IBaseUrl:

public interface IBaseUrl { string Get(); }

UWP 的 BaseUrl 实现,Windows Phone 8.1 和 Windows 8.1,取自 Windows Phone 8.0 sample project:

[assembly: Dependency(typeof(MyApp.UWP.BaseUrl))]
namespace MyApp.UWP
{
    public class BaseUrl : IBaseUrl
    {
        public string Get()
        {
            return ""; // "ms-appx-web:///Assets/" doesn't work
        }
    }
}

我尝试了 "ms-appx-web:///Assets/"、"ms-appx-web:///" 的返回 BaseUrl 的不同变体,将文件放在项目根目录或“资产”目录中,但没有任何效果。

据我所知,这曾经适用于 Windows Phone 8.0.

Device.OnPlatform呢?

var urlIos = @"somePicture.png";
var urlAndroid = @"somePicture.png";
var urlUWP = @"ms-appx-web:///Assets/somePicture.png";
htmlSource.Html = string.Format(@"<html><body><img src='{0}' /></body></html>", Device.OnPlatform(urlIos, urlAndroid, urlUWP));

从 Xamarin Forms 2.3.1 开始,Windows RT 的 WebViewRenderer 会简单地忽略 BaseUrl(https://github.com/xamarin/Xamarin.Forms/blob/2.3.1/Xamarin.Forms.Platform.WinRT/WebViewRenderer.cs#L26). However, there is a fix for this on the 2.3.2 branch: https://github.com/xamarin/Xamarin.Forms/blob/2.3.2/Xamarin.Forms.Platform.WinRT/WebViewRenderer.cs