我正在尝试将对象添加到组合框中并使用 SelectedValue 属性来选择组合框中的项目,但它不起作用: 选定值
SelectedValue
选定值
class ComboBoxItem { string name; object value; public string Name { get { return name; } } public object Value { get { return value; } } public ComboBoxItem(string name, object value) { this.name = name; this.value = value; } public override bool Equals(object obj) { ComboBoxItem item = obj as ComboBoxItem; return item!=null && Value.Equals(item.Value); } } operatorComboBox.Items.Add(new ComboBoxItem("Gleich", SearchOperator.OpEquals)); operatorComboBox.Items.Add(new ComboBoxItem("Ungleich", SearchOperator.OpNotEquals)); operatorComboBox.ValueMember="Value"; //SelectedValue is still null after this statement operatorComboBox.SelectedValue = SearchOperator.OpNotEquals;
ValueMember 仅在通过数据绑定时适用 DataSource Items.Add
ValueMember
DataSource
Items.Add
var items = new List<ComboBoxItem>(); items.Add(new ComboBoxItem(...)); operatorComboBox.DataSource = items;
顺便说一句,请注意,当您覆盖 Equals ,您还应该重写并实现 GetHashCode .
Equals
GetHashCode