by brad
20. October 2010 04:00
Today’s tip comes from my own curiosity. In most of the samples and examples for navigation in Windows Phone 7, we see code that looks a lot like this
1: NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.RelativeOrAbsolute));
The constructor for a Uri takes a string that represents the URI and a member of the UriKind enumeration. In most samples, the UriKind is set to UriKind.RelativeOrAbsolute. If you’ve ever been curious as to what exactly this meant and what other choices there might be, then this is the blog post for you.
UriKind basics
There are three choices for the UriKind:
- UriKind.Absolute: Includes the complete URI (in the case of a web page, think of “http://www.example.com/default.html”)
- UriKind.Relative: Includes only enough information to find the Uri relative to something else (again, in the case of a web page, think “/default.html”)
- UriKind.RelativeOrAbsolute: You just don’t know – could be either. The official term is “indeterminate”.
UriKind for Windows Phone Navigation
Given this, it looks like the Uri in the code sample above is a relative Uri and sure enough, if you specify the UriKind as relative, navigation works just as expected.
1: // Works just fine
2: NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));
On the other hand, if you specify the UriKind as absolute, navigation definitely does not work.
1: // Throws an argument exception
2: NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Absolute));
The specific argument exception is “Navigation is only supported to relative URIs that are fragments, or begin with '/', or which contain ';component/'.” This hints that there might be some cases where you can use absolute UriKinds, so if you know what those cases are, please share in the comments.
And one last thing: If not specified, the default for UriKind is UriKind.Absolute, so you can’t create a new Uri using only the Uri string.
Other Resources
More Tips