如何保存页面状态

本文关键字:状态 保存 何保存 | 更新日期: 2023-09-27 18:28:54

在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"));
    }
}

因此,它会导航到同一页面,但会显示新的追随者。

问题是,当它导航回来时,它会再次加载数据,并从列表的开头显示,而不是显示最后一个选择的项目。

那么,如何在NavigationHelper_SaveState中保存数据的List,以及如何在列表中最后一个位置的NavigationHelper_LoadState中再次加载数据呢?谢谢

如何保存页面状态

下面是一个基本的半测试示例。你需要修改它以适应你的具体情况。其中一些是根据这里改编的。

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