将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
:
- 在“
Properties
文件夹中将项目文件添加到项目中,或者如果已将其打开。 - 添加名为
CheckedItems
的字符串设置属性 - 在表单的
Load
事件中,从设置中读取选中的项目,并使用SetItemChecked
在CheckedListBox中设置选中的项目。 - 在
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)
因此,我们无法为此属性做更好的解决方法。
更多信息:
上述就是C#学习教程:将CheckedListBox项目保存到设置分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1011383.html