我相信这是一个非常简单的任务,我在网上看到了很多例子,但由于我遇到了不同的异常情况,所以它们都无法为我工作。
html:
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<p>
Help html content.
</p>
</body>
</html>
xaml:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<WebView x:Name="webView" />
<Button x:Name="buttonRefresh"
Grid.Row="1"
HorizontalAlignment="Center"
Click="buttonRefresh_Click">
Refresh
</Button>
</Grid>
为了在我的UWP应用程序LocalFolder中显示保存在
help.html
文件中的静态html,我已经尝试了以下方法:
- 使用Navigate方法:
private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
var uri = new Uri("ms-appdata:///local/help.html");
webView.Navigate(uri);
}
而结果是以下异常:
System.ArgumentException: Value does not fall within the expected range.
at Windows.UI.Xaml.Controls.WebView.Navigate(Uri source)
at SimpleUwpApp.Proxy.SimplerPage.buttonRefresh_Click(Object sender, RoutedEventArgs e)
- 尝试在代码后台明确设置webView的Source属性:
private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
var uri = new Uri("ms-appdata:///local/help.html");
webView.Source = uri;
}
结果:
System.ArgumentException: Value does not fall within the expected range.
at Windows.UI.Xaml.Controls.WebView.put_Source(Uri value)
at SimpleUwpApp.Proxy.SimplerPage.buttonRefresh_Click(Object sender, RoutedEventArgs e)
- 在xaml中明确设置webView的源属性:这是来自微软文档的精确示例。
<WebView x:Name="webView" Source="ms-appdata:///local/help.html" />
启动时出现异常:
Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found.
Failed to assign to property 'Windows.UI.Xaml.Controls.WebView.Source' because the type 'Windows.Foundation.String' cannot be assigned to the type 'Windows.Foundation.Uri'. [Line: 16 Position: 54]
at Windows.UI.Xaml.Application.LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)
at SimpleUwpApp.Proxy.SimplerPage.InitializeComponent()
- 尝试将url字符串直接用作Navigate()
参数,就像这个微软示例中所示,但是Navigate()
只接受Uri
作为参数,因此文档要么无效,要么适用于旧版本的xaml工具包。
webView.Navigate("ms-appx-web:///help.html");
结果:
Syntax error.
我暂时想到的唯一解决方案是使用某种文件管理器读取HTML文件的内容,并使用
NavigateToString()
方法:var content = fileManager.Read("help.html"); // Manually read the content of html file
webView.NavigateToString(content);
所以问题是为什么描述的示例不起作用?如何避免使用NavigateToString?