[英]How to save changes to ObservableCollection stored in Properties.Settings
使用簡單的世界時鍾程序使我遇到了一個問題,即如何在程序運行之間持久保存Clock
對象的自定義ObservableCollection
。 我可以成功保存其他設置類型,例如Strings,Doubles和Boolean,但是ObservableCollection
不會在程序會話之間保存。
不會引發任何錯誤,調試器值似乎可以正常更新( Properties.Settings.Default.SavedClocks
計數增加),並且時鍾無問題地添加到顯示的列表中。
這個問題使我想到了下面的當前代碼結構。
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控件我設置的的ItemSource
<ListView Name="lvDataBinding">
嘗試將SettingsSerializeAs
屬性添加到SettingsSerializeAs
中的SavedClocks
屬性,以指定應將集合序列化為二進制數據:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Binary)]
[global::System.Configuration.DefaultSettingValueAttribute(null)]
public ObservableCollection<Clock> SavedClocks
{
get
{
return ((ObservableCollection<Clock>)(this["SavedClocks"]));
}
set
{
this["SavedClocks"] = value;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.