DataBindings的问题,请解释一下

Jua*_*uan 4 .net c# data-binding winforms

public partial class Form1 : Form
{
    MyClass myClass = new MyClass("one", "two");

    public Form1()
    {
        InitializeComponent();
        textBox1.DataBindings.Add("Text", myClass, "Text1", false, DataSourceUpdateMode.Never);
        textBox2.DataBindings.Add("Text", myClass, "Text2", false, DataSourceUpdateMode.Never);
    }

    private void saveButton_Click(object sender, EventArgs e)
    {
        myClass.Text1 = textBox1.Text;
        myClass.Text2 = textBox2.Text;
        //textBox1.DataBindings["Text"].WriteValue();
        //textBox2.DataBindings["Text"].WriteValue();
    }
}

public class MyClass : INotifyPropertyChanged
{
    private string _Text1;
    private string _Text2;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Text1
    {
        get { return _Text1; }
        set { _Text1 = value; OnPropertyChanged(new PropertyChangedEventArgs("Text1")); }
    }

    public string Text2
    {
        get { return _Text2; }
        set { _Text2 = value; OnPropertyChanged(new PropertyChangedEventArgs("Text2")); }
    }

    public MyClass(string text1, string text2)
    {
        Text1 = text1;
        Text2 = text2;
    }

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null) PropertyChanged(this, e);
    }
}
Run Code Online (Sandbox Code Playgroud)

我觉得很清楚我想要实现的目标.我希望我的表单保存我的两个TextBoxes中所做的更改myClass.但每当我按编辑这两个文本框后的保存按钮,并且saveButton_Click被调用时,第二个textBox2Text可以追溯到原始文本('二’).我尝试使用BindingWriteValue功能,但同样的事情发生了.使用.net 4.0.

编辑感谢您的回答,但我不需要解决方法.我自己可以找到它们.我只需要了解一下绑定是如何工作的.我想明白为什么会这样?

Jef*_*ata 5

显然,更新数据源上的任何值都将导致更新所有绑定.这解释了行为(设置myClass.Text1导致textBox2使用当前值更新myClass.Text2).不幸的是,我能找到的几篇文章只是说,"这就是它的工作原理".

处理此问题的一种方法是创建一个BindingSource,设置BindingSource.DataSource = myClass,然后将TextBox绑定到BindingSource.

BindingSource如果基础数据源是列表并且项目已添加,删除等,或者属性发生更改,则会引发ListChanged事件.您可以通过将BindingSource.RaiseListChangedEvents设置为来禁止这些事件,这将允许您在不更新绑定控件的数据绑定的情况下设置多个属性.DataSourcefalsemyClass

public partial class Form1 : Form
{
    MyClass myClass = new MyClass("one", "two");
    BindingSource bindingSource = new BindingSource();

    public Form1()
    {
        InitializeComponent();

        bindingSource.DataSource = myClass;

        textBox1.DataBindings.Add("Text", bindingSource, "Text1", true, DataSourceUpdateMode.Never);
        textBox2.DataBindings.Add("Text", bindingSource, "Text2", true, DataSourceUpdateMode.Never);                
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bindingSource.RaiseListChangedEvents = false;
        myClass.Text1 = textBox1.Text;
        myClass.Text2 = textBox2.Text;
        bindingSource.RaiseListChangedEvents = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

HTH