C# TextBox 的数据绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1616003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Data binding for TextBox
提问by Joan Venge
I have a basic property that stores an object of type Fruit:
我有一个存储 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");
}
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.Food
,它会正确更新。如果我以编程方式修改 UI,如:
this.textBox.Text = "NewFruit"
, it doesn't update this.Food.
this.textBox.Text = "NewFruit"
,它不会更新 this.Food。
Why could this be? I also implemented INotifyPropertyChanged
for Fruit.Name, but still the same.
为什么会这样?我也INotifyPropertyChanged
为 Fruit.Name实现了,但还是一样。
采纳答案by Joepro
I Recommend you implement INotifyPropertyChanged and change your databinding code to this:
我建议您实现 INotifyPropertyChanged 并将您的数据绑定代码更改为:
this.textBox.DataBindings.Add("Text",
this.Food,
"Name",
false,
DataSourceUpdateMode.OnPropertyChanged);
That'll fix it.
这样就可以解决了。
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.
请注意,默认DataSourceUpdateMode
值为OnValidation
,因此如果您未指定OnPropertyChanged
,则模型对象将在您的验证发生后才会更新。
回答by Hasani Blackwell
You can't databind to a property and then explictly assign a value to the databound property.
您不能将数据绑定到属性,然后显式地为数据绑定属性分配一个值。
回答by Mickey Perlstein
You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.
您需要一个 bindingsource 对象作为中介并协助绑定。然后不是更新用户界面,而是更新下划线模型。
var model = (Fruit) bindingSource1.DataSource;
model.FruitType = "oranges";
bindingSource.ResetBindings();
Read up on BindingSource and simple data binding for Windows Forms.
阅读 BindingSource 和Windows Forms 的简单数据绑定。
回答by user3838082
We can use following code
我们可以使用以下代码
textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
Where
在哪里
"Text"
– the property of textboxmodel
– the model object enter code here"Name"
– the value of model which to bind the textbox.
"Text"
– 文本框的属性model
– 模型对象在此处输入代码"Name"
– 绑定文本框的模型值。