如何保存页面状态?

时间:2014-11-04 01:26:13

标签: c# windows-runtime windows-phone windows-store-apps windows-phone-8.1

在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中再次加载列表中的最后一个位置?感谢。

1 个答案:

答案 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;
    }
}