将CheckedListBox项目保存到设置

我试图维护用户设置中的CheckedListBox中的已检查项目列表,然后在应用程序加载时重新加载它们。

在我的Settings.settings文件中,我添加了以下内容:

    

并且,在chkList_ItemCheck ,我正在执行以下操作:

 Properties.Settings.Default.obj = chkList.Items; Properties.Settings.Default.Save() 

但出于某种原因,当我退出应用程序,重新打开,并检查Properties.Settings.Default.obj的值时,它为null

我做错了什么/错过了什么?

由于CheckedListBox.CheckedItems属性不能绑定到设置,因此您应该添加字符串属性并将选中的项目存储为设置中的逗号分隔字符串,并在关闭表单时保存设置并在表单Load中设置CheckedListBox的选中项目。

要保存CheckedListBox CheckedItems

  1. 在“ Properties文件夹中将项目文件添加到项目中,或者如果已将其打开。
  2. 添加名为CheckedItems的字符串设置属性
  3. 在表单的Load事件中,从设置中读取选中的项目,并使用SetItemChecked在CheckedListBox中设置选中的项目。
  4. FormClosing事件中,读取CheckedListBox的CheckedItems并将设置保存为逗号分隔的字符串。

码:

 private void Form1_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Properties.Settings.Default.CheckedItems)) { Properties.Settings.Default.CheckedItems.Split(',') .ToList() .ForEach(item => { var index = this.checkedListBox1.Items.IndexOf(item); this.checkedListBox1.SetItemChecked(index, true); }); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { var indices = this.checkedListBox1.CheckedItems.Cast() .ToArray(); Properties.Settings.Default.CheckedItems = string.Join(",", indices); Properties.Settings.Default.Save(); } 

我怎么知道它不能与设置绑定?

作为第一个证据,对于设计器模式中的每个控件,在属性网格中,您可以检查+( ApplicationSettings )( PropertyBinding )[…]以查看支持属性绑定的属性列表。

此外,您应该知道“ 应用程序设置使用Windows窗体数据绑定体系结构来提供设置对象和组件之间的设置更新的双向通信。 ” [1]

例如,当您将CheckedListBox BackColor属性绑定到MyBackColor属性时,以下是Designer为其生成的代码:

 this.checkedListBox1.DataBindings.Add( new System.Windows.Forms.Binding("BackColor", global::StackSamplesCS.Properties.Settings.Default, "MyBackColor", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); 

现在让我们看一下属性定义[2] :

 [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public CheckedListBox.CheckedItemCollection CheckedItems { get; } 

无法分配属性或索引器CheckedListBox.CheckedItems ,因为它是只读的

有没有更好的办法?

这个属性的简短回答是否定的。

假设我们有一个属性MyCheckedItems

 [UserScopedSetting()] public CheckedListBox.CheckedItemCollection MyCheckedItems { get { return ((CheckedListBox.CheckedItemCollection)this["MyCheckedItems"]); } set { this["MyCheckedItems"] = (CheckedListBox.CheckedItemCollection)value; } } 

我们如何设置提供程序实例化CheckedListBox.CheckedItemCollection

CheckedListBox.CheckedItemCollection类型没有定义公共构造函数

所以我们无法实例化它。 CheckedListBox内部使用它的唯一构造函数是[2] :

 internal CheckedItemCollection(CheckedListBox owner) 

此外,将项添加到此集合的唯一方法是CheckedItemCollection的内部方法:

 internal void SetCheckedState(int index, CheckState value) 

因此,我们无法为此属性做更好的解决方法。

更多信息:

  • 对于设计器模式中的每个控件,在属性网格中,您可以检查+( ApplicationSettings )( PropertyBinding )[…]以查看支持属性绑定的属性列表。
  • 设置序列化以这种方式工作,它首先尝试在类型的关联TypeConverter上调用ConvertToStringConvertFromString 。 如果这不成功,则使用XML序列化。 [1]因此,如果您没有遇到只读属性或无构造函数的类,则可以使用自定义TypeConverter或自定义序列化程序序列化值。