C# 在WinForm 中简单实现双向绑定 VM
/// <summary> /// 将绑定数据源和控件绑定 /// </summary> /// <param name="ctl">控件</param> /// <param name="propertyName">属性名称</param> /// <param name="BindingSource">数据源</param> /// <param name="fieldName">绑定字段</param> public static void SetDataBinding(this System.Windows.Forms.Control ctl, string propertyName, object BindingSource, string fieldName) { if (ctl.DataBindings[propertyName] != null) { ctl.DataBindings.Remove(ctl.DataBindings[propertyName]); } ctl.DataBindings.Add(propertyName, BindingSource, fieldName, true, DataSourceUpdateMode.OnPropertyChanged); } /// <summary> /// 移除绑定属性 /// </summary> /// <param name="ctl"></param> /// <param name="propertyName"></param> public static void RemoveDataBinding(this System.Windows.Forms.Control ctl, string propertyName) { if (ctl.DataBindings[propertyName] != null) { ctl.DataBindings.Remove(ctl.DataBindings[propertyName]); } }
调用
ComboBox.SetDataBinding("Text", Models, "字段名称");
当修改了model 的时候再重新执行
ComboBox.SetDataBinding("Text", Models, "字段名称");