TextBox 的数据绑定 [英] Data binding for TextBox
问题描述
我有一个基本属性来存储一个 Fruit 类型的对象:
I have a basic property that stores an object of type Fruit:
Fruit food;
public Fruit Food
{
get {return this.food;}
set
{
this.food= value;
this.RefreshDataBindings();
}
}
public void RefreshDataBindings()
{
this.textBox.DataBindings.Clear();
this.textBox.DataBindings.Add("Text", this.Food, "Name");
}
所以我在表单外设置了 this.Food
然后它显示在 UI 中.
So I set this.Food
outside the form and then it shows up in the UI.
如果我修改this.Food
,它会正确更新.如果我以编程方式修改 UI,例如:
If I modify this.Food
, it updates correctly. If I modify the UI programmatically like:
this.textBox.Text = "NewFruit"
,它不会更新 this.Food.
this.textBox.Text = "NewFruit"
, it doesn't update this.Food.
为什么会这样?我还为 Fruit.Name 实现了 INotifyPropertyChanged
,但还是一样.
Why could this be? I also implemented INotifyPropertyChanged
for Fruit.Name, but still the same.
推荐答案
我建议您实现 INotifyPropertyChanged 并将您的数据绑定代码更改为:
I Recommend you implement INotifyPropertyChanged and change your databinding code to this:
this.textBox.DataBindings.Add("Text",
this.Food,
"Name",
false,
DataSourceUpdateMode.OnPropertyChanged);
这就解决了.
注意默认的DataSourceUpdateMode
是OnValidation
,所以如果你不指定OnPropertyChanged
,模型对象直到在您进行验证之后.
Note that the default DataSourceUpdateMode
is OnValidation
, so if you don't specify OnPropertyChanged
, the model object won't be updated until after your validations have occurred.
这篇关于TextBox 的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!