|
Today I had the pleasure of presenting a web cast on building an application with more than one page and passing data among those pages. I have 2 videos on this topic, so if you missed the web cast and are interested, you may find this first video on switching pages of interest, and the second video should be posted soon. Multi-Page In A Nutshell The premise is that there is a third page that has no content and when it is time to display one of your pages, you make the page you want to display (which is, after all, a UserControl) the content of that third page (I’ve chosen to name the third page PageSwitcher but of course you may call it anything you like. PageSwitcher has a method, Navigate that takes a UserControl and makes whatever you pass in, its content. The implementation for the button on each page is to make the page you are switching to the new content. Passing Values Because we destroy the current page when we replace it (to conserve on client-side resources) if we wish to pass information (such as the book name, authors, whether the book is published and whether or not it is fiction) the easiest way is to make PageSwitcher the temporary repository; and the most efficient way to do that is to overload the navigate method to take an Object so that you may pass in anything at all, and then fish it out when your new page is loaded (very effective, very efficient and not at all type safe!). To see this at work, assume the user has filled out the fields as shown in Page 1 and clicked switch. The event handler for the button might look a bit like this: void SwitchButton_Click( object sender, RoutedEventArgs e ) { PageSwitcher ps = this .Parent as PageSwitcher; if ( ps != null ) { Book b = new Book(); b.BookName = BookName.Text; b.Authors = Authors.Text; b.isPublished = IsPublished.IsChecked == true ; b.isFiction = Fiction.IsChecked == true ; ps.Navigate( new Page2(),b ); } We know that our “parent” is the PageSwitcher as we are its content, and so the cast is safe (but being good o-o programmers we check (Доверяй, но проверяй) We then spin up a Book instance (defined off camera and fill in the properties from the user-filled in fields and then call the overloaded Navigate method, providing a new instance of Page2 and our newly filled in book. We trust PageSwitcher to (a) abandon Page.xaml and make Page2 its content and to hold onto whatever we’ve passed it until Page2 asks for it (think Secretkeeper in Harry Potter). When Page2 is safely established...
|