Thursday, July 8, 2010

Restoring a Windows State When Navigating Back to a Page

When navigating to another page and back again using the Silverlight Navigation Framework, sometimes it is useful to return to the page and see it exactly as it was.  Fortunately, this is easy to do if you are using an MVVM framework. 

When navigating away from the page, save the ViewModel in the App.Current.Resources collection.


protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (App.Current.Resources["theViewModel"] != null)
App.Current.Resources.Remove("theViewModel");
App.Current.Resources.Add("theViewModel", this.DataContext);
base.OnNavigatedFrom(e);
}

When returning to the page, pull it back out again and assign it to the page.


         protected override void OnNavigatedTo(NavigationEventArgs e)  
{
if (App.Current.Resources["theViewModel"] != null)
this.DataContext = App.Current.Resources["theViewModel"];
}

No comments:

Post a Comment