我在表单上有多个下拉式组合框,用户可以在其中指定与值关联的单位(例如米、英尺等)。为此,我在 Settings.Settings 中使用应用程序字符串集合以及一些默认单元类型,这些单元类型绑定(bind)到 ComboBox 的数据源,如下所示:
this.cboUnit.DataSource =
(System.Collections.Specialized.StringCollection)Properties.Settings.Default.Units;
用户能够成功选择一个单位或指定一个新单位。
现在,当我将 this.cboUnit.Text
保存到某个 XML 配置文件中时,我能够处理这两种情况。打开 XML 配置文件并执行 this.cboUnit.Text = "NonExistentUnit";
将失败并导致选择集合中的第一项。
如何修改 ComboBox 以支持我所要求的行为类型,无需将项目添加到 ComboBox 或修改数据源本身?
Using ComboBox.Text when combobox is tied to DataSource中建议了一个解决方案但我找不到支持这种行为的官方文档。因此,我宁愿避免它。
最佳答案
我找不到任何有效的方法将项目插入绑定(bind)的数据源。因此,我最终做了以下事情:
BindingSource bindingSource = new BindingSource((System.Collections.Specialized.StringCollection)Properties.Settings.Default.Units, "");
if(!bindingSource.Contains(someSavedValue))
{
bindingSource.Insert(0, someSavedValue));
}
this.cboUnit.DataSource = bindingSource;
这将创建绑定(bind)源的新实例,可以在将其绑定(bind)到数据源之前对其进行修改。我将此代码包装在一个方法中,我可以为其传递字符串集合和存储值(在本例中为 savedUnit
),该值返回新的 BindingSource 实例。这对我来说特别有用,因为我现在可以简单地写:
this.cboLengthUnit.DataSource = CreateBindingSource(unitsCollection, savedLengthUnit);
this.cboWidthUnit.DataSource = CreateBindingSource(unitsCollection, savedWidthUnit);
this.cboHeightUnit.DataSource = CreateBindingSource(unitsCollection, savedHeightUnit);
上面的代码是我凭内存写的,所以可能有错误。
关于c# - 如何将 ComboBox 文本设置为数据源 (C#) 中不存在的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537571/