Sdílet prostřednictvím


Passing a URI to the Windows Runtime

Windows Runtime methods accept only absolute URIs. If you pass a relative URI to a Windows Runtime method, an ArgumentException exception is thrown. Here's why: When you use the Windows Runtime in .NET Framework code, the Windows.Foundation.Uri class appears as System.Uri in Intellisense. The System.Uri class allows relative URIs, but the Windows.Foundation.Uri class does not. This is also true for methods you expose in Windows Runtime Components. If your component exposes a method that takes a URI, the signature in your code includes System.Uri. However, to users of your component, the signature includes Windows.Foundation.Uri. A URI that is passed to your component must be an absolute URI.

This topic shows how to detect an absolute URI and how to create one when referring to a resource in the app package.

Detecting and using an absolute URI

Use the Uri.IsAbsoluteUri property to ensure that a URI is absolute before passing it to the Windows Runtime. Using this property is more efficient than catching and handling the ArgumentException exception.

Using an absolute URI for a resource in the app package

If you want to specify a URI for a resource that your app package contains, you can use the ms-appx or ms-appx-web scheme to create an absolute URI.

The following example shows how to set the Source property for a WebView control and the Source property for an Image control to resources that are contained in a folder named Pages, using both XAML and code.

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <WebView Name="webview1" HorizontalAlignment="Center" Height="222"  
             VerticalAlignment="Top" Width="310" Margin="472,57,553,0"
             Source="ms-appx-web:///Pages/HTMLPage1.html"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="322,185,0,0" 
            VerticalAlignment="Top" Click="Button_Click_1"/>
<Image HorizontalAlignment="Left" Height="100" Margin="208,123,0,0" VerticalAlignment="Top" 
           Width="100" Source="ms-appx:///Pages/weather.jpg" />

</Grid>
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    webview1.Source = new Uri("ms-appx-web:///Pages/HTMLPage2.html", UriKind.Absolute);
}
Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
    webview1.Source = New Uri("ms-appx-web:///Pages/HTMLPage2.html", UriKind.Absolute)
End Sub

For more information about these schemes, see URI schemes in the Windows Dev Center.

See also