I'm using an implementation of Master/Detail in my Forms app. The problem is that even after I change pages the previous one is still running, I even had to do some inactive/isActive code in order to stop the code execution of those pages.
This is how I change pages:
public void GoTo(Page page)
{
Detail = new NavigationPage(page);
IsPresented = false;
UserDialogs.Instance.HideLoading();
}
Then I do:
Application.Current.HomePage.GoTo(new ServiceSelectionPage());
But the previous page is kept running. What am I doing wrong? Or how do I remove those pages from memory? I tried setting Detail = null to no avail.
Thanks!
It is by design. You could:
Set their instances to null, then wait for garbage collection. You could force it with GC.Collect(); - but it's not guaranteed.
Reuse pages instances (use same Page instance and only change current BindingContext). You could use custom Page Factory for that.
Related
I've already tried to find anything about that problem but I guess I either was not sure how to shortly describe the problem to find a solution or nobody else had that before which I can't think of. Maybe my thinking is wrong, too.
I have a stateless wicket 1.6 form with an ajax supporting panel (WebMarkupContainer with output id). The panel holds a dataview with paging navigator. The dataview itself is filled by a DataProvider.
The panel shows some entries from the database and below that is the navigator. by clicking any page on the navigator, the panel is refreshed (ajax) and shows content from that page. The page itself is not re-rendered by the browser.
When I now leave the page by navigating to another internal page (so basically when leaving the dataview-panel-page in any way) to open a detail page or so and then return to that dataview-page the navigator is resetted (because it's stateless I guess). The navigator can't remember which page to show and begins at the top of the first page again.
The question is: How can I solve this? I would like to i.ex. navigate to page 2 and then temporary leave the page for another internal page. When returning I want to be on page 2, focussed on the record where I clicked the link to "details" before. This also happens when I just open a new page in a new Browser tab.
Thank you!
Here's some code:
final WebMarkupContainer gamesPanel = new AjaxContainer("gamesPanel");
final DataView<Game> dataView =
new GameDataView("gameOverview", targetCurrencyModel, searchTextModel, gameFilterModel,
new GameDataProvider(searchTextModel, gameFilterModel, targetCurrencyModel));
dataView.setItemsPerPage(ITEMS_PER_PAGE);
gamesPanel.add(dataView);
final XNPagingNavigator navigator = new XNPagingNavigator("navigator", dataView);
navigator.setOutputMarkupId(true);
add(navigator);
You guys can try what I mean: The page I'm talking about is http://www.xbox-now.de. Just navigate to page 2, then click on details and return to main page.
I think you might use History API to push a new state when you click on navigation bar. In the new URL for the state you can include a parameter that indicates the index of the current navigator page.
You can customize your AJAX link in order to perform this operations when user click on it.
For more details on History API see Updating address bar with new URL without hash or reloading the page
I solved this in the NoWicket framework by introducing a model aware page cache which reuses page instances when hashcode/equals matches in the page model. You can see the implementation in the GitHub repo, try this implementation of the IPageFactory wrapper as a starting point, but it is more code involved there, just check out the code, debug the example and navigate the code to understand it better in order to apply it to your application. See your use case in action by trying this data table example in the documentation website (which you can also debug locally): http://invesdwin.de/nowicket/ajaxdatatable
Try changing the paging index, navigate to a different page and navigate back to the data table example page. You will still see the paging index that you left there.
Thank you guys for your replies. I've done it now another way. Used the base code from here and modified it in some ways. Added some nice css AttributeModifiers to indicate the actual page:
item.add(new AttributeModifier("class", new PageLinkCssModel(pageable, pageIndex, "active")));
Then I modified some code to add or reset the page parameter, that it's 1) used only once and 2) keeps all the actual page parameters which were there before adding own ones. So I am just appending the page number now. This way I can keep my initially mount path like www.foo.bar/path/path/path. Complete URL would now look like: www.foo.bar/path/path?page=123.
To pass my entered page (i.e. page=5) to the data provider I just had to override the providers iterator. It should start with the page I entered. Due to the ugly generated navigator URLs (which are extremly bad for SEO) I now have nice looking urls which are working independently what wasn't possible before. And that's also the reason why I could not get back to the correct page. The navigator URL was not lookup-able by wicket.
new DataView<GamePrice>("gamePriceOverview", new GameDetailDataProvider(gameId, targetRegion) {
#Override
public Iterator<GamePrice> iterator(final long first, final long count) {
return super.iterator(ITEMS_PER_PAGE * getCurrentPage(), count);
}
getCurrentPage() comes from the base template and gets the actual page number entered (if one is entered):
public long getCurrentPage() {
// -1 weil zero based
return getRequest().getQueryParameters().getParameterValue("page").toString() != null
? (getRequest().getQueryParameters().getParameterValue("page").toLong() - 1)
: 0;
}
So instead of having ugly SEO-unfriendly URLs which are also not compatible to work independant (directly enter the generated url) I now have the same URL I expect with an added page-parameter.
URL now would looks like:
http://localhost:8080/game/4249/de/doom-preorder?page=2
URL before was:
localhost:8080/game/4249/DE/doom-preorder?0-1.ILinkListener-gamePrices-navigator-navigation-2-pageLink
If I now go back from the detail page to the main index with active "Bookmarkable-Navigator", I correctly come back to the page and position where I left it (because of bookmarkable page links).
That's how I achieved this problem with a nice bonus: User- and SEO-friendly URLs.
This is a question regarding navigation between pages in Windows 8 app -
How can I avoid the re-creation of the page when navigating between pages ?
For example - Whether I'm using frame.Navigate(typeof(MyPage1), null); or Frame.GoBack(); (after switching to another page from MyPage1), a new instance of MyPage1 will be created.
I want to avoid it in order to keep the same UI state in MyPage1. Using MVVM, I can restore most of it, but not all... (for instance, selected item in a tree). How can this be done ?
Put this in the constructor of the page that you do not want destroyed:
this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
Is there a best practice for handling tombstoning and back key properly?
As it is stated in the MSDN docu you should save transient data in the OnNavigatedFrom method. Ok, so the code for saving states when tombstoning is clear.
But now if you press the back key the OnNavigatedFrom method is also called and if you don't add extra checks, you will first save states into the dictionary and shortly after that the page will be destroyed. And so will the PhoneApplicationPage.State dictionary. So the saving code is completely wasted CPU, disk and battery time.
This is what I've done to prevent it:
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
// when navigating back
if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
{
backKeyPressed = true;
}
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
if (backKeyPressed)
{
// Don't save states on back key!
backKeyPressed = false; // set it anyway
return;
}
// Tombstoning
// save objects
this.SaveState("text", someText);
...
}
As a reminder: OnNavigatingFrom will only be called when navigating away/back from the page but not when app gets tombstoned.
Side note: Shown code covers only pages that can only navigate back. Thats why I added backKeypressed to OnNavigatingFrom. You need extra checks if the page can navigate to another page.
Is there a better way to do this for every page you create?
Now do I really have to add the backKeyPressed variable and check on every page I create?
Shouldn't the framework provide something for us developer so we don't have to worry much about this?
What are your thoughts about this?
EDIT:
Updated question the make it clearer.
your approach of checking the direcetion of navigation in OnNavigatingFrom is indeed the recommended practice in order to avoid the unneccessary performance hit of saving state just before the page gets removed from the backstack.
There is one clarification I want to add to your sample code: You should check the 'NavigationMode' property in the 'NavigationCancelEventArgs' to determine whether it's a forward or backward navigation.
Then only save the state in OnNavigatedFrom if it was a forward navigation, as your sample shows. This will help improve your performance when the user navigates backwards.
Everything you ever needed to know about tombstoning is covered in Jeff Prorise's 4-part Real-World Tombstoning in Silverlight for Windows Phone 7 blog post series. You may want to pay particular attention to part 2 where Jeff talks about clearing up state when the application quits.
I'm looking for the best practice on how to pass data from page to page.
In Page A I have a button that fires off Page B.
On Page B I have 6 textboxes that allow the user to enter information.
When the user is done, the click on a button that brings them back to Page A.
I want to pass that data back to Page A.
I've seen suggestions to:
build XML documents and save to Isolated Storage
use the App class to store information in properties
pass it like a query string
I'm looking for the Best practice. Is there one that Microsoft recommends or one that is generally accepted as the best way?
Thanks
PhoneApplicationService.Current.State["yourparam"] = param
NavigationService.Navigate(new Uri("/view/Page.xaml", UriKind.Relative));
then in other page simply
var k = PhoneApplicationService.Current.State["yourparam"];
Personally I'd store the values entered on Page B in a model(object) that is also accessible to Page A.
Depending on how you're navigating to Page A the second time, one or more of the following may be usful to help understand passing values between pages:
How to pass the image value in one xaml page to another xaml page in windows phone 7?
Passing a complex object to a page while navigating in a WP7 Silverlight application
How to pass an object from a xaml page to another?
How to pass a value between Silverlight pages for WP7?
How do I navigate from one xaml page to another, and pass values?
One thing you can consider is to use MVC: let your App be the controller, store all data in the model, and the pages are just views that contains pure UI logic. In this case your pages are painters and you pass your model object around. This gives nice isolation of business logic and the UI so that you can rev them easily.
BTW, Silverlight and XAML are great tools for MVC so it's a natural match.
There's a couple of things at play here. First of all, if/when the user uses the Back button to return to page A instead of your button, is the information in the text boxes exchanged or not (is Back = Cancel, or is Back = OK?)
That said, if you're using NavigationService.GoBack (which you should be instead of NavigationService.Navigate, because if you use the Navigate call, repeated hits of the back key will cause all kinds of bad UX for your users), then QueryStrings are not an option. Because pages really have no way to reference each other in the WP7 Silverlight nav system, you need to use a 3rd party to hold your data. For that, you can turn to (a) Isolated Storage (slow & heavy, but fail-safe), (b) Use the PhoneApplicationService.State dictionary, or (c) use Global properties of some kind, either hung off of the application object, or using Statics/Singletons...
Remember to watch for Tombstoning behavior when you do this - your page will process the OnNavigatedTo method when (a) you navigate into it in your application (b) you navigate back to it when you complete your work on Page B, or (c) you tombstone your app from that page and return to your application using the Back key.
Sorry I didn't give a more direct answer there - a lot depends on your specific circumstances. In the most general case, I'd strongly consider using the App State Dictionary on the PhoneApplicationService...it is lightweight, easy to use, and survives tombstoning. Just be sure that your keys are as unique as they need to be.
If you create a new Windows Phone project and use the Windows Phone Databound Template you will have most of the work done for you.
What you will want to do is set up the ViewModel to contain all the data for your app. You can serialize and deserialize this data using IsolatedStorage so that it's saved across application sessions and when Tombstoning.
In the template you will notice MailViewModel and ItemViewModel. MainViewModel stores all the data your application needs including an ObservableCollection of ItemViewModel, and ItemViewModel represents the individual data type for your application.
On the DetailsPage.xaml page you'll want to DataBind each textbox to the App.MainViewModel Items. Set the binding to TwoWay if you want the ViewModel to get updated as soon as the user manipulates the data on DetailsPage.xaml. You can optionally set the Binding to OneWay and then have an OK button that writes the changes back to the ViewModel and saves to IsolatedStorage.
Here is an example of what a Binding looks like:
<TextBlock x:Name="ListTitle" Text="{Binding LineOne}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
In this case LineOne is a property in ItemViewModel and the page gets this data from the query string when the user selects an item from the MainPage.xaml. The DataContext for the page determs where the databound information comes from.
Here is the snippet where the MainPage passes the selected item from the ViewModel to the DetailsPage.
// Handle selection changed on ListBox
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected index is -1 (no selection) do nothing
if (MainListBox.SelectedIndex == -1)
return;
// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
// Reset selected index to -1 (no selection)
MainListBox.SelectedIndex = -1;
}
Here is how the DetailsPage gets the selected item.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
int index = int.Parse(selectedIndex);
DataContext = App.ViewModel.Items[index];
}
}
Play around with the default template above and ask any additional questions.
The beauty of databinding and the ObservableCollection is that you can just update the data and the UX will reflect those changes immediatley. This is because any changes to the data fires off an event:
public string LineOne
{
get
{
return _lineOne;
}
set
{
if (value != _lineOne)
{
_lineOne = value;
NotifyPropertyChanged("LineOne");
}
}
}
NotifyPropertyChanged() that broadcasts this information to the View.
You can also keep it simple and use PhoneApplicationService.Current.State which is basically a hashtable. You will need to implement your own marshalling to and from isolated storage if you want anything to outlive the app.
Omar's suggestion to use the Windows Phone Databound Template is probably the best idea on this page. It amounts to the same as my suggestion but you will get a better result (more maintainable code) at the cost of a longer steeper learning curve.
I suggest you do it my way and then do it again Omar's way.
as i implemented like this.. Whether its correct or not i dont know..
When u click news list page it should open the news detail page.
I want to pass the selected news item contents from news List-Page to news-details Page.
the News list page contains following method.
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
NewsDetailsPage newsDetailPage = (e.Content as NewsDetailsPage);
if (newsDetailPage != null)
newsDetailPage.SelectedNewsItem = SelectedNewsItem; //Contains the news details
base.OnNavigatedFrom(e);
}
In the News details Page. U can access that(SelectedNewsItem) object.
This may or may not be correct.
One option is to use Application.Resources:
Store data:
Application.Current.Resources.Add("NavigationParam", customers);
NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
Retrieve data:
var customers = (List<Customer>) Application.Current.Resources["NavigationParam"];
Here's a blog post with describes this in more detail: http://mikaelkoskinen.net/windows-phone-pass-data-between-pages-application-resources/ (author: me)
I'm using IsolatedStorageSettings on WP7 to store an objects list:
List<T>
I need to search an item inside my list and to update some properties of the searched item.
I'm using this code:
List<Article> listArt = null;
IsolatedStorageSettings.ApplicationSettings.TryGetValue("ArticleListStorage", out listArt);
var queryList = (from anItem in listArt where (anItem.Id == _id) select anItem).ToList<Article>();
a = queryList[0] as Article;
//mark Article as read
a.Readed = true;
When I continuously navigate the various page inside the app, I can see the property Readed correctly evalued.
But, when I click on WP7 Start button and reopen my app (without close emulator) I see the property not correctly evalued.
Need I to update my object inside list and so inside Isolated Storage?
Not updated by reference?
I tried also this, ant it doesn't work:
listArt[0].Readed = true;
listArt[0].Favorite = true;
IsolatedStorageSettings.ApplicationSettings["ArticleListStorage"] = listArt;
IsolatedStorageSettings.ApplicationSettings.Save();
What is wrong?
Thank you so much!
You can either explicitly call Save() on the settings or wait for the app to close normally and then they will be saved automatically.
As a general rule I'd suggest always explicitly saving settings once you change them. (Unless you have a very good reason not to.)
What's happening in your situation is that you are pressing the start button which causes your app to tombstone. When you launch a new instance of the app the tombstoned version is destroyed without all the code which normally runs on application close (including auto-saving settings) being executed.
Here's and example of using Save:
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("some-key"))
{
settings.Remove("some-key");
}
settings.Add("some-key", "my-new-value");
settings.Save();
Yes, you've got to save your list again. Think of isolated storage as a file system - you wouldn't expect to be able to load an XDocument from disk, make changes in memory and automatically see those changes reflected on disk, would you? Well, it's the same with isolated storage.