关于在存储wp 8.1中保存数据

时间:2015-08-10 03:49:44

标签: c# visual-studio silverlight windows-phone-8.1

我在同一个3页p1 + p2 + p3:

中创建了这段代码
public partial class P1 : PhoneApplicationPage
{
    IsolatedStorageSettings UserDatas = IsolatedStorageSettings.ApplicationSettings;
    int point;
    int level;

    public P1()
    {
        InitializeComponent();
        this.Loaded += P1_Loaded;
    }

    private void P1_Loaded(object sender, RoutedEventArgs e)
    {
        if (UserDatas.Contains("Points") && UserDatas.Contains("Levels"))
        {

            PBlock.Text = "Point: " + UserDatas["Points"];
            LBlock.Text = "Levels: " + UserDatas["Levels"];
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        point = point + 5;
        level = level + 1;
        UserDatas["Points"] = point + 5;
        UserDatas["Levels"] = level + 1;

        NavigationService.Navigate(new Uri("/Views/P2.xaml", UriKind.Relative));
    }
}

}

单击按钮并转到p2 [point = 5,level = 1] 并直接单击按钮并转到p3输出[point = 10,level = 2] 但是当我转到第4页时,输出仍然是P3,为什么?

1 个答案:

答案 0 :(得分:2)

你的第4页的输出正是应该是的。

事实上,根据您的代码/逻辑,之后导航的所有页面都将包含point = 10level = 2

原因很简单,当调用构造函数时,pointlevel都设置为0。在Button_Click函数中,您的值分别增加了5和1。因此更新后的值为5和1.现在您已将point + 5level + 1放在UserDatas中。因此point始终为10,level为2。

注意:如果您尝试为每个页面导航增加5点并逐级增加1,只需将Button_Clink函数替换为以下代码段:

private void Button_Click(object sender, RoutedEventArgs e)
{
    UserDatas["Points"] = UserDatas["Points"] + 5;
    UserDatas["Levels"] = UserDatas["Levels"] + 1;

    NavigationService.Navigate(new Uri("/Views/P2.xaml", UriKind.Relative));
}