问题
I'm having a bit of trouble loading an html file in a WebView control in a metro style app. I've been searching the internet and found out that you can't load a local html file with the NavigateTo method. I also found out that there is a workaround in which you can use the NavigateToString method of the control. Below is the link where i saw this: http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/9cd8614d-2dc8-48ac-9cd9-57b03a644930
Someone in a post on that topic gave an example on how this could be done. They used and a byte array in which they put the data they obtained from calling the IInputstream.ReadAsync method. The problem I've ran into is that after i call that method the byte array is full of 0's, which i don't think is ok. Can anyone help me with this?
回答1:
You can switch contexts by using the ms-appx-web:///
protocol instead of ms-appx:///
, which I've had successfully loading local Html files and associated CSS and JavaScript, within a HTML/JS Metro Style App.
I've not tried this in a XAML Metro Style App, but believe that the ms-appx-web:///
protocol can be used. The limitation is that your Html (if local i.e not web hosted) has to reside within a WinRT package, which it appears to in your case i.e. /Assets.
回答2:
I ran into the same problem. In my application I have a file called Default.html which is read and it's contents are displayed in a WebView control.
var html = await Windows.Storage.PathIO.ReadTextAsync("ms-appx:///Assets/Default.html");
MyWebView.NavigateToString(html);
Note that I'm using await
and ReadTextAsync
so that the code is asynchronous (as one should when doing IO), the function you place this snipped it must be defined as async, example:
private async void LoadWebView( file ) { ... }
回答3:
Here is a quick sample tell me if this help you:
I have an Html file in my Assets folder called MyHTMLPage, it has a build action of type content and a Copy to Output to Copy Always. My Html file:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div style="background-color: chartreuse">HELLO WORLD, from a webview</div>
</body>
</html>
On my Main Page.xaml:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<WebView x:Name="MyWebView" Width="200" Height="300"></WebView>
</Grid>
On my Main Page.cs:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
string src = "ms-appx-web:///Assets/MyHTMLPage.html";
this.MyWebView.Navigate(new Uri(src));
}
}
and Voila this should work.
来源:https://stackoverflow.com/questions/10684741/load-local-html-file-in-webview-metro-style-app