我试图将对象添加到组合框中,并使用SelectedValue属性选择组合框中的项目,但它不起作用:分配后SelectedValue仍然为null。

        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手动添加项目的情况。尝试这个:

var items = new List<ComboBoxItem>();
items.Add(new ComboBoxItem(...));

operatorComboBox.DataSource = items;


顺便说一句,请注意,当您覆盖Equals时,还应该覆盖并实现GetHashCode

关于c# - ComboBox SelectedValue属性不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3140910/

10-11 02:18