如何将TextBox绑定到整数?例如,将单位绑定到textBox1。
public partial class Form1 : Form
{
int unit;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.DataBindings.Add("Text", unit, "???");
}
答案 0 :(得分:22)
它需要是实例的公共属性;在这种情况下,“this”就足够了:
public int Unit {get;set;}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.DataBindings.Add("Text", this, "Unit");
}
对于双向通知,您需要UnitChanged
或INotifyPropertyChanged
:
private int unit;
public event EventHandler UnitChanged; // or via the "Events" list
public int Unit {
get {return unit;}
set {
if(value!=unit) {
unit = value;
EventHandler handler = UnitChanged;
if(handler!=null) handler(this,EventArgs.Empty);
}
}
}
如果您不希望它出现在公共API上,您可以将其包装在某个隐藏类型中:
class UnitWrapper {
public int Unit {get;set;}
}
private UnitWrapper unit = new UnitWrapper();
private void Form1_Load(object sender, EventArgs e)
{
textBox1.DataBindings.Add("Text", unit, "Unit");
}
有关信息,“事件列表”的内容类似于:
private static readonly object UnitChangedKey = new object();
public event EventHandler UnitChanged
{
add {Events.AddHandler(UnitChangedKey, value);}
remove {Events.AddHandler(UnitChangedKey, value);}
}
...
EventHandler handler = (EventHandler)Events[UnitChangedKey];
if (handler != null) handler(this, EventArgs.Empty);
答案 1 :(得分:5)
您可以使用绑定源(请参阅注释)。最简单的变化是:
public partial class Form1 : Form
{
public int Unit { get; set; }
BindingSource form1BindingSource;
private void Form1_Load (...)
{
form1BindingSource.DataSource = this;
textBox1.DataBindings.Add ("Text", form1BindingSource, "Unit");
}
}
但是,如果您稍微分离出数据,您将获得一些概念清晰度:
public partial class Form1 : Form
{
class MyData {
public int Unit { get; set; }
}
MyData form1Data;
BindingSource form1BindingSource;
private void Form1_Load (...)
{
form1BindingSource.DataSource = form1Data;
textBox1.DataBindings.Add ("Text", form1BindingSource, "Unit");
}
}
HTH。注意省略了访问修饰符。
答案 2 :(得分:4)
我喜欢做的一件事就是为表单创建“表示”层。我在这一层声明了绑定到表单上控件的属性。在这种情况下,控件是一个文本框。
在这个例子中,我有一个带有文本框的表单来显示IP地址
我们现在通过文本框属性创建绑定源。选择DataBindings-> Text。单击向下箭头;选择“添加项目数据源”。
这将启动数据源向导。选择对象。点击“下一步”。
现在选择具有将绑定到文本框的属性的类。在此示例中,我选择了 PNetworkOptions 。选择“完成”以结束向导。将不会创建BindingSource。
下一步是从绑定类中选择实际属性。从DataBindings-> Text,选择downarrow并选择将绑定到文本框的属性名称。
在具有您的属性的类中,必须实现INotifyPropertyChanged以进行IP地址字段的双向通信
public class PNetworkOptions : IBaseInterface, INotifyPropertyChanged
{
private string _IPAddress;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public string IPAddress
{
get { return _IPAddress; }
set
{
if (value != null && value != _IPAddress)
{
_IPAddress = value;
NotifyPropertyChanged("IPAddress");
}
}
}
}
在表单构造函数中,我们必须专门定义绑定
Binding IPAddressbinding = mskTxtIPAddress.DataBindings.Add("Text", _NetOptions, "IPAddress",true,DataSourceUpdateMode.OnPropertyChanged);