繁体   English   中英

如何保存对存储在Properties.Settings中的ObservableCollection的更改

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM