When developing Metro-style applications (commonly referred to as Windows Store applications), it is a common requirement to load and display local HTML files using the WebView control. This can be achieved through several different methods. Below, I will detail a practical method along with specific examples.
Method: Using the ms-appx-web Protocol
In Windows Store applications, the WebView control supports special URI schemes such as ms-appx-web://, which is used to access resources within the application package. This means you can place HTML files in a specific folder within the project (e.g., the Assets folder) and load them via the WebView control.
Step-by-Step Instructions:
-
Prepare the HTML file:
Place the HTML file you want to load in the project's Assets folder. For example, assume you have a file namedexample.html. -
Modify the page's XAML code:
Add a WebView control to your XAML page and set itsSourceproperty to point to your HTML file using the ms-appx-web URI.xml<WebView x:Name="webView" Source="ms-appx-web:///Assets/example.html"/> -
Handle WebView navigation events (optional):
If you need to handle links or perform additional JavaScript interactions within the HTML page, you can process these in the WebView control's navigation events.csharpprivate void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { // Handle navigation events here, such as intercepting certain URLs. }
Example Code:
Below is a simple example demonstrating how to use WebView to load a local example.html file in a Windows Store application:
xml<Page x:Class="MyApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <WebView x:Name="webView" Source="ms-appx-web:///Assets/example.html"/> </Grid> </Page>
Important Notes:
- Ensure that the HTML file is correctly added to the project and its 'Build Action' property is set to 'Content' to ensure it is included in the application package.
- When using the ms-appx-web scheme, only resources within the package can be accessed. If external files need to be accessed, consider other approaches such as using a file picker.
By following these steps, you can successfully load local HTML files in your Metro-style application using the WebView control, providing rich content and interactive experiences.