Winform用于TextBox简单数据双向绑定的类
- 需要绑定的数据源定义为类属性
- 定义数据源关联的Binding并增加在Binding的List表中
- 包含数据绑定错误提示
绑定数据源类代码:
public class AssistData : INotifyPropertyChanged
{
private double _tiltX = 0;
public double TiltX
{
get
{
return this._tiltX;
}
set
{
this._tiltX = value;
this.SendChangeInfo("TiltX");
}
}
public List<Binding> Bindings = new List<Binding>();
public AssistData()
{
Bindings.Add(new Binding("Text", this, "TiltX", false, DataSourceUpdateMode.OnValidation));
foreach (Binding bd in Bindings)
{
bd.FormattingEnabled = true;
bd.FormatString = "F2";
bd.BindingComplete += new BindingCompleteEventHandler(this.BingComplete);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void SendChangeInfo(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void BingComplete(object sender, System.Windows.Forms.BindingCompleteEventArgs e)
{
if (e.BindingCompleteState != System.Windows.Forms.BindingCompleteState.Success)
{
System.Windows.Forms.MessageBox.Show(e.Binding.Control.Tag + "(" + e.Binding.Control.Text + ")" + ":" + e.ErrorText);
}
}
}
TextBox控件增加绑定
AssistData assistData = new AssistData();
this.textBox1.DataBindings.Add(this.assistData.Bindings[0]);
TextBox数量较多时使用很方便