2013-01-24 30 views
2

我是来自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; 
     } 
    } 

此方式设置“配置文件”可以正确保存和恢复。

但我不喜欢这种解决方案的原因:

  1. 这是一个黑客
  2. settings.designer.cs改变每次添加时间/删除设置
  3. 好,再次,这是一个黑客!

所以我猜这个问题是在序列化的地方。但是ObservableCollection可以完美地序列化,就像我们在例子中看到的那样。

P.S.我也尝试在设置设计器中浏览System.Collections.ObjectModel.ObservableCollection<tick_time.UserProfile>(tick_time是我的项目命名空间的名称),但我没有任何运气。

所以,我会很感激任何意见!

回答

1

经过一番更多的搜索后,我能够拿出更少的黑客解决方案。 我使用了http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/6f0a2b13-88a9-4fd8-b0fe-874944321e4a/的想法(请参阅最后一条评论)。

想法是修改不settings.Designer.cs,但专门创建另一个文件。自动生成Settings是部分的,所以我们可以在其他文件中完成它的定义。所以我只是让专用文件包含手动添加的属性!

它实际上工作。

所以现在我会把它当作答案。