2017-02-10 68 views
0

使用簡單的世界時鐘程序導致我遇到了如何在程序運行之間保留對象的自定義ObservableCollection的問題。我可以成功保存其他設置類型,如字符串,雙精度和布爾值,但ObservableCollection不會在程序會話之間保存。如何保存對Properties.Settings中存儲的ObservableCollection的更改

沒有錯誤拋出,調試器值似乎更新正常(Properties.Settings.Default.SavedClocks計數增加),並且時鐘被添加到顯示列表沒有問題。

question已導致我下面的代碼的當前結構。


enter image description here


Settings.Designer.cs- 手動創建

[global::System.Configuration.UserScopedSettingAttribute()] 
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 
public ObservableCollection<Clock> SavedClocks 
{ 
    get{ 
     return ((ObservableCollection<Clock>)(this["SavedClocks"])); 
    } 
    set{ 
     this["SavedClocks"] = value; 
    } 
} 

時鐘類定義

[Serializable] 
public class Clock : INotifyPropertyChanged 
{ 
    public string m_LocationName { get; set; } 
    public TimeZoneInfo m_TimeZone { get; set; } 

    public Clock(){} 

    public Clock(TimeZoneInfo tz, string name) 
    { 
     m_TimeZone = tz; 
     m_LocationName = name; 
    } 

    //.... Other methods removed for brevity 
} 

主窗口初始化

namespace WorldClock 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      if (Properties.Settings.Default.SavedClocks == null) 
      { 
       Properties.Settings.Default.SavedClocks = new ObservableCollection<Clock> 
       { 
        //When list is empty, default with local clock 
        new Clock(System.TimeZoneInfo.Local, System.TimeZoneInfo.Local.StandardName) 
       }; 

       Properties.Settings.Default.Save(); 
      } 

      lvDataBinding.ItemsSource = Properties.Settings.Default.SavedClocks; 
     } 
    } 
} 

添加新的時鐘觀察到的集合(從下拉列表)

private void btn_AddRegion_Click(object sender, RoutedEventArgs e) 
{ 
    TimeZoneInfo tz = timeZoneCombo.SelectedItem as TimeZoneInfo; 

    Properties.Settings.Default.SavedClocks.Add(new Clock(tz, tbx_RegionName.Text)); 
    Properties.Settings.Default.Save(); 
} 

XAML- 不要以爲任何這將是有用的,但這裏是ListView控件我設置

<ListView Name="lvDataBinding"> 
+0

爲了存儲數據,集合不需要被觀察到。在應用程序啓動過程中,您可以輕鬆地從存儲的List或數組中初始化ObservableCollection。另請參閱本文有關在應用程序設置中存儲自定義類型的文章:http://www.blackwasp.co.uk/customappsettings.aspx – Clemens

+0

@Clemens - 您鏈接的帖子是一個很好的來源,我已將其關注到信中,但不幸的是,它不能解決我的問題,即數據不會在運行之間持續存在。嘗試不同的類型是一種選擇,但我很想知道爲什麼我的方法不能按預期工作。 Thk –

+0

你的Clock類應該可能有一個無參數的構造函數。 – Clemens

回答

2

嘗試的的ItemSource到SettingsSerializeAs屬性添加到SavedClocks財產在Settings.Designer.cs中指定集合應該被序列化爲二進制數據:

+2

這讓我在駝峯,謝謝!對於其他任何人,我還需要在我的Clock類中爲公共事件PropertyChangedEventHandler PropertyChanged添加'[field:NonSerialized]'。 –

+0

這對我來說也是這樣! –