如何存储和使用应用程序对象windows phone 7/8?

时间:2013-09-07 07:55:40

标签: windows-phone-7 windows-phone-8 windows-phone-7.1

我有一个对象,我正在使用几乎所有的Windows手机页面,目前我正在使用

PhoneApplicationService.Current.State["xx"] = m_xx;
NavigationService.Navigate(new Uri("/abc.xaml", UriKind.Relative));

但必须为所有我不想要的活动做这件事。 有没有更好的方法来保存我可以在所有页面中使用的m_xx对象? 什么是最佳做法?

我可以将对象静态设置为某个类,然后通过该类名跨页面使用吗?

1 个答案:

答案 0 :(得分:2)

您可能希望了解MVVM模式。

但是,如果对应用程序进行了太多更改,则可以使用混合方法,将共享上下文存储在静态属性中。

首先,创建一个Context类并将您的共享属性放在其中:

public class Context
{
    public string SomeSharedProperty { get; set; }
}

然后,在App.xaml.cs中,创建一个静态属性来存储上下文:

private static Context context;

public static Context Context
{
    get
    {
        if (context == null)
        {
            context = new Context();
        }

        return context;
    }
}

然后,从应用程序的任何位置,您都可以访问上下文来存储/检索数据:

App.Context.SomeSharedProperty = "Hello world!";