Thanks for visiting my blog!
Url: http://wilderminds.blob.core.windows.net/downloads/backenabledsilv…
I’ve been teaching my students to be careful not to create Silverlight projects that alienate users and break the basic working of the web. One of the things I’ve explained is that you need to make it so that the back button and links work (where applicable) in your applications. I haven’t had a good example to show them until now.
I’ve created a quick and dirty example of how to change the address bar (and respond to this change when you return). The trick to getting this to work is to use the HtmlWindow’s CurrentBookmark and NavigateToBookmark members. For example, in the example I have a ListBox that changes some state in my app. When the SelectedIndex changes, I use NavigateToBookmark to change the Url:
theList.SelectionChanged += (s, e) =>
{
if (theList.SelectedItems.Count > 0)
{
siteInfo.Visibility = Visibility.Visible;
siteInfo.DataContext = theList.SelectedItem;
Site site = (Site) theList.SelectedItem;
HtmlPage.Window.NavigateToBookmark(string.Concat("id=", site.Id));
// HACK to fix non-binding of NaviateUri
theLink.NavigateUri = new Uri(site.Url);
}
else
{
siteInfo.Visibility = Visibility.Collapsed;
}
};
Then in my app, on Load I look at the CurrentBookmark so that if I’ve returned to my application with the Bookmark specified, I can change the state of my app back:
this.Loaded += (s, x) =>
{
// Show current item if included in bookmark
if (!string.IsNullOrEmpty(HtmlPage.Window.CurrentBookmark))
{
string[] parts = HtmlPage.Window.CurrentBookmark.Split('=');
if (parts.Length == 2)
{
int id;
if (int.TryParse(parts[1], out id))
{
Site selected = sites.FirstOrDefault(e => e.Id == id);
theList.SelectedItem = selected;
}
}
}
};
This is enabling both the Back button as well as Linking to my app. You can download the source here:
http://wilderminds.blob.core.windows.net/downloads/backenabledsilverlight.zip
Or see a live version of it here:
http://www.silverlightdata.com/backenabledsilverlight.aspx
One caveats on the example:
- When you return to the page with a bookmark, the ListBox selection isn’t showing. This is a ListBox bug that has been communicated to Microsoft. It has nothing to do with this code.