C#组合框和自己的类的双向绑定不起作用(有时)

时间:2019-02-13 14:52:00

标签: c# winforms data-binding combobox binding

我在将数据类的属性绑定到ComboBox控件的属性时遇到问题。

为了向您展示我的问题,我创建了一个新的WinFrom项目,它具有DropDownList样式的ComboBox(comboBox1)和两个按钮(button1和button2)。为了绑定数据,我遵循了本文的建议:

Binding property to control in Winforms

Two way databinding in winforms, Inotifypropertychanged implemented in base class

现在我的数据类如下:

public class Data : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // --- Properties ---
    // - value -
    public object value { get; set; }
    // - abc -
    private string _abc;
    public string abc
    {
        get { return _abc; }
        set
        {
            if (value != _abc)
            {
                _abc = value;
                NotifyPropertyChanged();
            }
        }
    }
}

...以及代码的另一部分:

Data MyDataSource = new Data();

public Form1()
{
    InitializeComponent();
    comboBox1.Items.AddRange(new string[] { "a", "b", "c" });
    comboBox1.DataBindings.Add(new Binding(nameof(comboBox1.Tag), MyDataSource, nameof(MyDataSource.value)));
    comboBox1.DataBindings.Add(new Binding(nameof(comboBox1.SelectedItem), MyDataSource, nameof(MyDataSource.abc)));
}

private void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("Value of _abc = " + MyDataSource.abc + " / comboBox1.SelectedItem = " + comboBox1.SelectedItem.ToString());
}

private void button2_Click(object sender, EventArgs e)
{
    MyDataSource.abc = "a";
}

您可以使用comboBox1选择一个值(a,b或c)。按下button1后,您可以看到例如:

Value of _abc = b / comboBox1.SelectedItem = b

一切都很好。如果按下button2,值a将被写入MyDataSource.abc,并且comboBox1也将被更新。按下button1的结果如下:

Value of _abc = a / comboBox1.SelectedItem = a

但是现在的问题是,您无法使用comboBox1将值改回另一个值。如果您尝试通过下拉菜单更改它,并保留焦点突出的ComboBox,则该值会跳回到a

要解决此问题,您可以执行以下操作:

Data MyDataSource = new Data();

public Form1()
{
    InitializeComponent();
    comboBox1.Items.AddRange(new string[] { "a", "b", "c" });
    //comboBox1.DataBindings.Add(new Binding(nameof(comboBox1.Tag), MyDataSource, nameof(MyDataSource.value)));
    comboBox1.DataBindings.Add(new Binding(nameof(comboBox1.SelectedItem), MyDataSource, nameof(MyDataSource.abc)));
}

Data MyDataSource = new Data();

public Form1()
{
    InitializeComponent();
    comboBox1.Items.AddRange(new string[] { "a", "b", "c" });
    comboBox1.DataBindings.Add(new Binding(nameof(comboBox1.SelectedItem), MyDataSource, nameof(MyDataSource.abc)));
    comboBox1.DataBindings.Add(new Binding(nameof(comboBox1.Tag), MyDataSource, nameof(MyDataSource.value)));   // now after the SelectedItem Binding
}

我的问题是,为什么会这样?

0 个答案:

没有答案