使用IsolatedStorageSettings为wp8中的应用程序永久存储信息

时间:2013-10-09 18:19:44

标签: c# windows windows-phone-8 isolatedstorage

我正在使用IsolatedStorageSettings存储我的应用中的密钥的联系人列表。但应用程序只存储列表,直到应用程序处于活动状态(即从一个页面导航到另一个页面)。如果我退出应用程序并再次重新启动它,则找不到存储的密钥/联系人列表。如何永久保存应用程序列表,直到安装该应用程序? 这是我的viewmodel的代码,我正在使用:

   public class ContactsViewModel : ViewModelBase
    {
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
        private List<SavedContact> _SavedContactsList;
        public ContactsViewModel()
        {

            Contacts cons = new Contacts();
            cons.SearchAsync(String.Empty, FilterKind.None, null);
            cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(OnContactSearchCompleted);
            SaveSavedContactsCommand = new RelayCommand(OnSaveSavedContacts);
        }


        private List<SavedContact> GetSavedContacts()
        {

            if (appSettings.Contains("SavedContacts"))
            {
                var savedContacts = (List<SavedContact>)appSettings["SavedContacts"];
                return savedContacts;
            }
            else
            {
                return new List<SavedContact>();
            }
        }
        public RelayCommand SaveSavedContactsCommand { get; set; }

        private void OnSaveSavedContacts()
        {
            if (!SavedContactsList.Any(x => x.IsSelected == true))
            {
                MessageBox.Show("Please select some contacts and then click on Save button.");
            }
            else
            {
                var selectedSavedContacts = SavedContactsList.Where(x => x.IsSelected == true).ToList();
                SavedContacts = selectedSavedContacts;
                MessageBox.Show("Emergency contact list added successfully.");

                App.RootFrame.GoBack();
            }
        }

        void OnContactSearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            try
            {
                SavedContactsList = new List<SavedContact>();
                var allContacts = new List<Contact>(e.Results.Where(x => x.PhoneNumbers.Count() > 0).OrderBy(c => c.DisplayName));
                // var savedContacts = GetSavedContacts();
                var savedContacts = SavedContacts;
                foreach (Contact contact in allContacts)
                {
                    SavedContact SavedContact = new SavedContact() { Contact = contact };
                    if (savedContacts.Any(x => x.Contact.PhoneNumbers.ElementAt(0).PhoneNumber == contact.PhoneNumbers.ElementAt(0).PhoneNumber))
                    {
                        SavedContact.IsSelected = true;
                    }
                    else
                    {
                        SavedContact.IsSelected = false;
                    }
                    SavedContactsList.Add(SavedContact);
                }

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in retrieving contacts : " + ex.Message);
            }

        }

        [DataMember]
        public List<SavedContact> SavedContactsList
        {
            get { return _SavedContactsList; }
            set
            {
                _SavedContactsList = value;
                RaisePropertyChanged("SavedContactsList");
            }
        }
        private List<SavedContact> SavedContacts
        {
            get
            {
                if (appSettings.Contains("SavedContacts"))
                {
                    var savedContacts = (List<SavedContact>)appSettings["SavedContacts"];
                    return savedContacts;
                }
                else
                {
                    return new List<SavedContact>();
                }
            }
            set
            {
                appSettings["SavedContacts"] = value;
            }
        }


    }

类SavedContact如下:

  [DataContract]
    public class SavedContact : INotifyPropertyChanged
    {
        public SavedContact() { }
        private bool _isSelected;
        private Contact _contact;

        [DataMember]
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    OnPropertyChanged("IsSelected");
                }

            }
        }

        [DataMember]
        public Contact Contact
        {
            get
            {
                return _contact;
            }
            set
            {
                if (_contact != value)
                {
                    _contact = value;
                    OnPropertyChanged("Contact");
                }

            }
        }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

视图模型绑定到<toolKit: LongListMultiSelector />的位置。功能就像,我从我的longlist multislector中选择一些联系人并将其保存在存储中以便以后重用。但是,如果我退出应用程序并重新启动它,savedContacts将返回null。当我浏览应用程序中的其他页面时,已保存的联系人正在打印。 如果我第一次保存列表,则在应用程序重新启动时,GetSavedContacts()将返回一个新列表。

2 个答案:

答案 0 :(得分:1)

此问题与IsolatedStorageSettings或您的RelayCommand无关。查看更详细的问题是Contact对象的序列化和反序列化。如果您将实现更新为类似下面的示例,那么您应该没问题。

public class ContactsViewModel : ViewModelBase
{
    private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

    private List<UserContact> _contactList;

    public ContactsViewModel()
    {

        Contacts cons = new Contacts();
        cons.SearchAsync(String.Empty, FilterKind.None, null);
        cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(OnContactSearchCompleted);
        SaveSavedContactsCommand = new RelayCommand(OnSaveSavedContacts);
    }

    public RelayCommand SaveSavedContactsCommand { get; private set; }

    private void OnSaveSavedContacts()
    {
        if (!Contacts.Any(x => x.IsSelected == true))
        {
            MessageBox.Show("Please select some contacts and then click on Save button.");
        }
        else
        {
            var selectedSavedContacts = Contacts.Where(x => x.IsSelected == true).Select(x => new SavedContact{ Name = x.Contact.DisplayName, PhoneNumber = x.Contact.PhoneNumbers.ElementAt(0).PhoneNumber}).ToList();
            SavedContacts = selectedSavedContacts;
            MessageBox.Show("Emergency contact list added successfully.");

            App.RootFrame.GoBack();
        }
    }

    void OnContactSearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        try
        {
            Contacts = new List<UserContact>();
            var allContacts = new List<Contact>(e.Results.Where(x => x.PhoneNumbers.Count() > 0).OrderBy(c => c.DisplayName));

            foreach (Contact contact in allContacts)
            {
                UserContact SavedContact = new UserContact() { Contact = contact };
                if (SavedContacts.Any(x => x.PhoneNumber == contact.PhoneNumbers.ElementAt(0).PhoneNumber))
                {
                    SavedContact.IsSelected = true;
                }
                else
                {
                    SavedContact.IsSelected = false;
                }
                Contacts.Add(SavedContact);
            }

        }
        catch (System.Exception ex)
        {
            MessageBox.Show("Error in retrieving contacts : " + ex.Message);
        }

    }

    [DataMember]
    public List<UserContact> Contacts
    {
        get { return _contactList; }
        set
        {
            _contactList = value;
            RaisePropertyChanged("Contacts");
        }
    }

    public List<SavedContact> SavedContacts
    {
        get
        {
            if (appSettings.Contains("SavedContacts"))
            {
                var savedContacts = (List<SavedContact>)IsolatedStorageSettings.ApplicationSettings["SavedContacts"];
                return savedContacts;
            }
            else
            {
                return new List<SavedContact>();
            }
        }
        set
        {
            if (value != null)
            {
                IsolatedStorageSettings.ApplicationSettings["SavedContacts"] = value;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }
    }
}

public class SavedContact
{
    public string Name { get; set; }

    public string PhoneNumber { get; set; }
}

[DataContract]
public class UserContact : INotifyPropertyChanged
{
    public UserContact() { }
    private bool _isSelected;
    private Contact _contact;

    [DataMember]
    public bool IsSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            if (_isSelected != value)
            {
                _isSelected = value;
                OnPropertyChanged("IsSelected");
            }

        }
    }

    [DataMember]
    public Contact Contact
    {
        get
        {
            return _contact;
        }
        set
        {
            if (_contact != value)
            {
                _contact = value;
                OnPropertyChanged("Contact");
            }

        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

答案 1 :(得分:0)

添加到应用程序的键/值对IsolatedStorageSettings将保持不变,直到卸载应用程序或从字典中删除该项目。这适用于应用程序重启和设备开机和关闭之间。

您的SaveList方法可以简化为下面的示例,因为只有在从设置字典中检索值时才需要检查.Contains,因为如果无法找到该条目,它将引发异常。

private void SaveList()
{
    appSettings["SavedContacts"] = urls;
}

或者,您可以使用属性来处理对IsolatedStorageSettings的所有访问,使用类似下面的示例:

private IList<Contact> Contacts
{
    get
    {
        return appSettings.Contains("SavedContacts") ? (List<Contact>)appSettings["SavedContacts"] : null;
    }
    set
    {
        appSettings["SavedContacts"] = value;
    }
}