Combox的选定值未更新

时间:2016-10-11 10:02:57

标签: c# windows data-binding

我需要将一个对象绑定到我的Combobox上,当我点击一个按钮时,我试图显示其选定的值或Current.color。这是我的代码

      public ObservableCollection<Data> Items { get; set; }
    public Data _current;
    public Data Current
    {
        get
        { return _current; }
        set
        {
            _current = value;
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("Current"));
            }
        }
    }
    public Form1()
    {
        InitializeComponent();
        Items = new ObservableCollection<Data>();
        for (int i = 0; i < names.Count; i++)
        {
            Items.Add(new Data() { color = names[i] });
        }
        combobox.DataSource=Items;
        comboBox1.DisplayMember = "Name";
        comboBox1.ValueMember = "color";
        Current = Items.First();
        comboBox1.DataBindings.Add("SelectedValue", Current, "color", true, DataSourceUpdateMode.OnValidation);
    }
    public List<Color> names = new List<Color>() { Color.Red, Color.Yellow, Color.Green, Color.Blue };

    public event PropertyChangedEventHandler PropertyChanged;
    private void button1_Click(object sender, EventArgs e)
    {
        label2.Text =Current.color.ToString();
        comboBox1.SelectedItem = Current;
    }

问题是标签“红色”只显示一次,当我将选择更改为其他颜色并返回到第一个时,Current.color不会更新为“红色”..我可以知道它为什么? ?

1 个答案:

答案 0 :(得分:1)

只有当SelectedValue属性不是默认值(即&#34; Red&#34;)时,才会触发代码中的propertyChanged事件。
发生这种情况是因为Current对象初始化为items.First()。

一种解决方案是使用新的Data对象初始化Current对象,即:

/client/

另一个解决方案是在Text属性上添加绑定而不是SelectedValue,即:

...
Current = new Data(){ color = Color.Red }
comboBox1.DataBindings.Add("SelectedValue", Current, "color", true, DataSourceUpdateMode.OnValidation);
...
相关问题