我相信這是非常簡單的任務,我在網上看到了很多示例,但仍然沒有一個適用於我,因爲我遇到了不同的例外情況。在UWP WebView中顯示本地html文件內容
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我已經試過如下:
- 使用導航方法:
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)
- 嘗試設置web視圖的源屬性明確在後面的代碼:
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 web視圖的設置源屬性:這是microsoft documentation確切的例子。
<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()
論據,在此microsoft examples嘗試,但Navigate()
只Uri
這樣的文件或者是接受作爲aargument對舊版本的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?
可能的重複[在UWP中從應用程序數據本地文件夾中的xaml中加載WebView中的Html文件](http://stackoverflow.com/questions/35626840/loading-html-file-in-webview-in-xaml -in-uwp-from-app-data-local-folder) –