Silverlight Tip of the Day #41: Using Bookmarks in your Silverlight Application
Bookmarks are very useful in web sites because they allow people to directly navigate back to a section of the web site they visited before. This tip will show you how to apply and use bookmarks in Silverlight applications.
For example, if a user types in http://www.MySilverlightApp.com/default.aspx#Page2 you would intercept this from the address bar and show the second page of your application.
For our demo, for simplicity sakes, we will just make each page it’s own Canvas element with a TextBlock. Ideally you would probably want to make each page its own UserControl. I have created two pages: Page1 and Page2.
Page.xaml:
<UserControl x:Class="SilverlightApplication14.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas>
<Canvas x:Name="Page1">
<TextBlock>Hello there this is page 1</TextBlock>
</Canvas>
<Canvas x:Name="Page2" Visibility="Collapsed">
<TextBlock>Hello there this is page 2</TextBlock>
</Canvas>
</Canvas>
</UserControl>
In the constructor of Page.xaml.cs we call ProcessBookmark(). This routine will get the bookmark string from the address bar by calling HtmlPage.Window.CurrentBookmark; Once we know what the bookmark is we can set the Visiblity of the Canvas we want displayed to Visible. Note that we also set the title bar of the browser window by calling HtmlPage.Document.SetProperty("title", _page1Title);
public partial class Page : UserControl
{
const string _page1Title = "My Silverlight App - Page 1";
const string _page2Title = "My Silverlight App - Page 2";
public Page()
{
InitializeComponent();
ProcessBookmark();
}
private void ProcessBookmark()
{
string bookMark = HtmlPage.Window.CurrentBookmark;
switch (bookMark)
{
case "Page1":
HtmlPage.Document.SetProperty("title", _page1Title);
Page1.Visibility = Visibility.Visible;
Page2.Visibility = Visibility.Collapsed;
break;
case "Page2":
HtmlPage.Document.SetProperty("title", _page2Title);
Page1.Visibility = Visibility.Collapsed;
Page2.Visibility = Visibility.Visible;
break;
}
}
}
So what if you want to set the address bar to a bookmark? You can change the string in the address bar of your browser with the following call: HtmlPage.Window.Eval("window.location.hash='Page1'");
More specifically:
1: private void SetBookmark(string bookmark)
2: {
3: HtmlPage.Window.Eval("window.location.hash='"+bookmark+"'");
4: }
Currently if you hit the back button in your browser it will exit you out of your Silverlight. I am looking into a way to intercept the Back and Forward buttons in your browser so that we can create a history of bookmarks internal to our Silverlight application. If anyone has some good resources/techniques let me know and I will incorporate the functionality into this blog.
Thank you,
--Mike Snow
Subscribe in a reader