【发布时间】:2015-03-09 22:05:25
【问题描述】:
我正在尝试通过显示本地 html 文件来测试 WebView。问题是,webview 没有显示任何内容。
我的XAML 部分如下所示:
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock x:Name="onlineTestHeadingText"
Text="Welcome to online test!"
FontSize="24"
Foreground="Red"/>
<WebView x:Name="onlineTestWebView"
/>
</StackPanel>
</Grid>
C# 部分是:(已编辑:相对路径已更正)
public sealed partial class OnlineTest : Page
{
Uri url;
public OnlineTest()
{
this.InitializeComponent();
}
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
url = onlineTestWebView.BuildLocalStreamUri("myUrl", "/problem_page/test.html");
StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
onlineTestWebView.NavigateToLocalStreamUri(url, myResolver);
}
}
Helper 类的实现是:
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
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
{
Uri localUri = new Uri("ms-appx:///html" + path);
StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
}
catch (Exception) { throw new Exception("Invalid path"); }
}
}
【问题讨论】:
-
上述xaml和c#的唯一问题是我没有将html文件的属性设置为“内容”
标签: c# xaml windows-phone-8 webview