我觉得很清楚我在试图实现。我想要我的表单将我的两个 TextBox es中所做的更改保存到 myClass 。但是每当编辑两个文本框后,按下保存按钮,并且调用 saveButton_Click ,则第二个 textBox2 code>文本返回到原始文本(两)。我尝试使用绑定的 WriteValue 函数,但同样的事情发生。使用 4.0。
I think is pretty clear what I'm trying to achieve. I want my form to save the changes made in my two TextBoxes to myClass. But whenever I press the save button after editing both text boxes, and saveButton_Click is invoked, the second textBox2's Text goes back to the original text ("two"). I tried using Binding's WriteValue function but the same thing happens. Using 4.0.
编辑感谢您的回答,但我不需要解决方法。我可以自己找到他们我只需要了解一些更好的绑定工作。我想了解为什么会发生这种情况?
Edit Thanks for your answers, but I don't need workarounds. I can find them myself. I just need to understand a little bit better how binding works. I would like to understand why is this happening?
推荐答案显然,更新数据源上的任何值都会导致所有绑定更新。这解释了行为(设置 myClass.Text1 导致 textBox2 更新为当前值 myClass.Text2 )。不幸的是,我能够发现的几个帖子几乎只是说:这就是它的工作原理。
Apparently, updating any value on the data source will cause all bindings to be updated. This explains the behavior (setting myClass.Text1 causes textBox2 to be updated with the current value of myClass.Text2). Unfortunately, the few posts I was able to find pretty much just said, "that's how it works".
一种处理方法是创建一个 BindingSource ,设置 BindingSource.DataSource = myClass ,然后将您的文本框绑定到 BindingSource 。
One way to handle this is to create a BindingSource, set BindingSource.DataSource = myClass, and then bind your TextBoxes to the BindingSource.
BindingSource raise ListChanged 事件,如果基础数据源是列表,项目被添加,删除等,或如果 DataSource 属性更改。您可以通过设置 BindingSource.RaiseListChangedEvents 到 false ,这将允许您在 myClass 上设置多个属性,而无需更新绑定控件的数据绑定。
BindingSource raises ListChanged events if the underlying data source is a list and items are added, removed, etc., or if the DataSource properties change. You can suppress these events by setting BindingSource.RaiseListChangedEvents to false, which would let you set multiple properties on myClass without data-binding updating the bound controls.
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; } }HTH
更多推荐
DataBindings的问题,请解释
发布评论