我有以下课程
公共级汽车 { 公共名称{get; 放;} }
我想以编程方式将此绑定到文本框。
我怎么做?
在黑暗中拍摄:
... 汽车 car = new Car(); TextEdit 编辑框 = new TextEdit(); editBox.DataBinding.Add("名称", car, "汽车 - 名称"); ...
我收到以下错误
“无法绑定到目标控件上的属性‘名称’。
我做错了什么,我应该怎么做?我发现来自网络开发的数据绑定概念有点难以掌握。
我有以下课程
公共级汽车 { 公共名称{get; 放;} }
我想以编程方式将此绑定到文本框。
我怎么做?
在黑暗中拍摄:
... 汽车 car = new Car(); TextEdit 编辑框 = new TextEdit(); editBox.DataBinding.Add("名称", car, "汽车 - 名称"); ...
我收到以下错误
“无法绑定到目标控件上的属性‘名称’。
我做错了什么,我应该怎么做?我发现来自网络开发的数据绑定概念有点难以掌握。
你要
editBox.DataBindings.Add("Text", car, "Name");
第一个参数是要绑定的控件的属性名称,第二个是数据源,第三个参数是要绑定到的数据源的属性。
不看语法,我很确定它是:
editBox.DataBinding.Add("Text", car, "Name");
editBox.DataBinding.Add("Text", car, "Name");
第一个 arg 是控件属性的名称,第二个是要绑定的对象,最后一个是要用作数据源的对象属性的名称。
您非常接近数据绑定行
editBox.DataBinding.Add("Text", car, "Name");
第一个参数是将数据绑定的编辑框对象的属性。第二个参数是要绑定的数据源,最后一个参数是要绑定的数据源的属性。
请记住,数据绑定是一种方式,因此如果您更改编辑框,则汽车对象会更新,但如果您直接更改汽车名称,则不会更新编辑框。
尝试:
editBox.DataBinding.Add( "Text", car", "Name" );
我相信
editBox.DataBindings.Add(new Binding("Text", car, "Name"));
应该做的伎俩。没试过,但我认为是这样的。
您正在尝试绑定到 TextEdit 控件的“名称”。该名称用于以编程方式访问控件,不能绑定。您应该对控件的文本进行绑定。
使用 C# 4.6 语法:
editBox.DataBinding.Add(nameof(editBox.Text), car, nameof(car.Name));
如果 car 为 null,则上述代码将以比使用文字字符串表示datamember
of更明显的方式失败car
以下是可用作属性的泛型类,并实现了绑定控件使用的 INotifyPropertyChanged 来捕获属性值的变化。
public class NotifyValue<datatype> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
datatype _value;
public datatype Value
{
get
{
return _value;
}
set
{
_value = value;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Value"));
}
}
}
可以这样声明:
public NotifyValue<int> myInteger = new NotifyValue<int>();
并分配给这样的文本框
Textbox1.DataBindings.Add(
"Text",
this,
"myInteger.Value",
false,
DataSourceUpdateMode.OnPropertyChanged
);
..其中“Text”是文本框的属性,“this”是当前的 Form 实例。
类不必继承 INotifyPropertyChanged 类。声明 System.ComponentModel.PropertyChangedEventHandler 类型的事件后,控件数据绑定器将订阅类更改事件
它是
this.editBox.DataBindings.Add(new Binding("Text", car, "Name"));