C# – 将TextBox绑定到整数

如何将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, "???"); } 

它需要是一个实例的公共财产; 在这种情况下,“this”就足够了:

 public int Unit {get;set;} private void Form1_Load(object sender, EventArgs e) { textBox1.DataBindings.Add("Text", this, "Unit"); } 

对于双向通知,您需要UnitChangedINotifyPropertyChanged

 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); 

您可以使用绑定源(请参阅注释)。 最简单的变化是:

 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。 注意省略了访问修饰符。

我喜欢做的一件事是为表单创建“表示”层。 我在这一层声明了绑定到表单上控件的属性。 在这种情况下,控件是一个文本框。

在这个例子中,我有一个带有文本框的表单来显示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);