c# - 不为资源调用 NavigateToLocalStreamUri

标签 c# css webview uwp

我在 WebView 中使用 NavigateToLocalStreamUri,这样我就可以为浅色和深色主题加载特定的样式表。我像这样格式化我的 HTML 文件:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="css/main.css" />
    <link rel="stylesheet" type="text/css" href="css/theme-(RequestedTheme).css" />
</head>
<body>
...
</body>
</html>

这里是我的StreamUriResolver代码如下:

public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
    if (uri == null)
    {
        throw new ArgumentException("Uri cannot be empty");
    }
    string path = uri.AbsolutePath;
    // Because of the signature of the this method, it can't use await, so we 
    // call into a seperate helper method that can use the C# await pattern.
    return GetContent(path).AsAsyncOperation();
}

private async Task<IInputStream> GetContent(string path)
{
    // We use a package folder as the source, but the same principle should apply
    // when supplying content from other locations
    try
    {
        // Replace content modifiers with actual values
        path = path.Replace("(RequestedTheme)", Application.Current.RequestedTheme.ToString().ToLowerInvariant());
        Uri localUri = new Uri("ms-appx:///Content" + path);
        StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
        IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
        return stream.GetInputStreamAt(0);
    }
    catch (Exception) { throw new InvalidOperationException("Invalid path"); }
}

它是用这段代码调用的:

Uri uri = webViewer.BuildLocalStreamUri("Landing", url);
StreamUriResolver myResolver = new StreamUriResolver();

// Pass the resolver object to the navigate call.
webViewer.NavigateToLocalStreamUri(uri, myResolver);

我在 UriStreamResolver 中添加了一个断点,但是 GetContent 仅在 HTML 页面上命中一次,而不是针对页面上的样式表或图像。它们已加载并且图像显示正常,但条件样式表未加载。我读过的文章和帖子说每次需要加载资源时都应调用 GetContent,但我没有看到这种行为。

最佳答案

经过反复试验,我发现问题出在 <base> 的使用上在我的一些页面中添加标签。这导致网页在加载这些 Assets 时不使用解析器。删除 <base>标记并仅使用相对 URL 现在对需要加载的所有 Assets 使用解析器。

关于c# - 不为资源调用 NavigateToLocalStreamUri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000044/

相关文章:

c# - 在 C# Winforms 应用程序中调用 Application.Run 有好处吗?

html - 为选择提供与输入相同的轮廓样式

html - 覆盖链接样式

java - 无法在 android webview 中加载屏幕?

webview - React-native检测对WebView的单击

Android Studio Webview 不调用照片库

C# <exception> 标签不显示

c# - Linq to SQL 简单问题

c# - 需要在 SortedCollection 中允许重复(C#,2.0)

javascript - 当同时设置了 id 和 class 时,如何使组件使用特定的 css