【发布时间】:2020-03-31 22:31:40
【问题描述】:
目前正在使用 C# 构建一个 WinForms 数据收集工具,并且已经能够实现将我的下属对象/实体的属性的值绑定到我的表单上的控件,例如我的域模型类(例如 Person 类)上的属性的 TextBoxes、MaskedTextBoxes 和 Checkboxes。但是,我无法使用 ComboBox 控件成功完成此绑定。
我的 Person 类看起来基本上是这样的:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Gender { get; set; }
}
我正在使用 ComboBox 的 DataSource 属性绑定到 Dictionary 并相应地设置 ValueMember 和 DisplayMember。这样做会在运行时使用我的参考数据(显示值和编码值)成功填充该 ComboBox。
Dictionary<int, string> genderValues = repository.GetGenderValues()
cboGender.DataSource = new BindingSource(genderValues, null);
cboGender.ValueMember = "Key";
cboGender.DisplayMember = "Value";
但是,当我尝试将我的 Person 对象的属性“性别”绑定到此 ComboBox 时,遵循与其他控件类型(TextBox、CheckBox 等)一起使用的模式
cboGender.DataBindings.Add(new Binding("ValueMember", _currentPerson, "Gender"));
即使在选择了 Gender ComboBox 中的项目后,我的 person 对象上的 Gender 值也始终为 NULL。也许我忽略了将 ComboBox 的 ValueMember 绑定到对象属性所需的额外步骤?
【问题讨论】:
-
你到底想达到什么目的?
-
为什么不使用
List<Person>作为 BindingSource 的数据源(这样您就可以将它用于所有其他控件),将DisplayMember和ValueMember设置为您想要的属性作为项目的文本和相应的值?在这里使用(未定义的)字典有什么用?