我是来自C++世界的C#和.Net新手。我通过为自己创建一个小应用程序来学习C#WPF。无法保存自定义收集用户设置
目前我需要创建一个集合用户设置。因为之后,我想能够将此集合绑定到列表框,我决定使用ObservableCollection。
至此之后相当长的一段搜索这里是我有:
public class ProfileStorage : ApplicationSettingsBase
{
public ProfileStorage()
{
this.UserProfiles = new ObservableCollection<UserProfile>();
}
[UserScopedSetting()]
[SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Binary)]
[DefaultSettingValue("")]
public ObservableCollection<UserProfile> UserProfiles
{
get
{
return (ObservableCollection<UserProfile>)this["UserProfiles"];
}
set
{
this["UserProfiles"] = value;
}
}
}
[Serializable]
public class UserProfile
{
public String Name { get; set; }
}
我甚至能够浏览它设置的设计者和创建一个名为“ProfileStorage”设置。这里是在settings.designer.cs中自动创建的代码:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::tick_time.ProfileStorage ProfileStorage {
get {
return ((global::tick_time.ProfileStorage)(this["ProfileStorage"]));
}
set {
this["ProfileStorage"] = value;
}
}
问题是我无法保存此设置!我用下面的代码来检查。
if (null == Properties.Settings.Default.ProfileStorage)
{
Properties.Settings.Default.ProfileStorage = new ProfileStorage()
{
UserProfiles = new ObservableCollection<UserProfile>
{
new UserProfile{Name = "1"},
new UserProfile{Name = "2"}
}
};
Properties.Settings.Default.Save();
}
}
ProfileStorage始终为空。
所以这是我的问题。经过一番搜索后,我在Stackowerflow的一篇文章中发现了下面的黑客攻击。我需要手动更改settings.Designer.cs:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public ObservableCollection<UserProfile> Profiles
{
get
{
return ((ObservableCollection<UserProfile>)(this["Profiles"]));
}
set
{
this["Profiles"] = value;
}
}
此方式设置“配置文件”可以正确保存和恢复。
但我不喜欢这种解决方案的原因:
- 这是一个黑客
- settings.designer.cs改变每次添加时间/删除设置
- 好,再次,这是一个黑客!
所以我猜这个问题是在序列化的地方。但是ObservableCollection可以完美地序列化,就像我们在例子中看到的那样。
P.S.我也尝试在设置设计器中浏览System.Collections.ObjectModel.ObservableCollection<tick_time.UserProfile>
(tick_time是我的项目命名空间的名称),但我没有任何运气。
所以,我会很感激任何意见!