在Windows运行时应用中,我加载如下数据:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
然后用户可以从ListView
中选择一个项目:
private void ContentListView_ItemClick(object sender, ItemClickEventArgs e)
{
var selectedItem = e.ClickedItem as User;
if (!Frame.Navigate(typeof(FollowersPage), selectedItem.UserId))
{
throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
}
}
所以它导航到同一页面,但显示新的粉丝。
问题在于,当它向后导航时,它会再次加载数据并从列表的开头显示,而不是显示最后选择的项目。
那么如何在List
中保存NavigationHelper_SaveState
数据,以及如何在NavigationHelper_LoadState
中再次加载列表中的最后一个位置?感谢。
答案 0 :(得分:2)
这是一个可以从中开始的基本半测试示例。您需要对其进行修改以适合您的具体情况。其中一些改编自here。
void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
var isp = (ItemsStackPanel)listview.ItemsPanelRoot;
int firstVisibleItem = isp.FirstVisibleIndex;
e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
// This must be serializable according to the SuspensionManager
e.PageState["Followers"] = this.DefaultViewModel["Followers"];
}
void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Do we have saved state to restore?
if (e.PageState != null)
{
// Restore list view items
this.DefaultViewModel["Followers"] = (WhateverType)e.PageState["Followers"];
// Restore scroll offset
var index = (int)e.PageState["FirstVisibleItemIndex"];
var container = listview.ContainerFromIndex(index);
listview.ScrollIntoView(container);
}
else
{
// Load data for the first time
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
}