在我的Winform项目中,我有一个简单的细节表单,我们可以添加新的,编辑和保存持久对象,直到这里一切都很好。
编辑控件由from构造函数中的代码绑定,第一次创建时,表单构造函数也传递第一个新对象
现在我想实现保存和新方法,但没有成功
我试过这个,假设tbVehicule是对象类, theVehicule 是我的持久对象和frmVehicule我的详细信息表单
// Form Constructor
public frmVehicule(tbVehicule theVehicule)
: this() {
this.theVehicule = theVehicule;
// method to bind all controls
bindingFields();
}
// Save and new method
private void barBtnSaveNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.Validate();
theVehicule.Save();
theVehicule = new tbVehicule(theVehicule.Session);
}
该过程应该类似于其他ORM,如EF或Hibernate
答案 0 :(得分:1)
我自己解决了这个问题,所以我回答了我的问题,希望它会帮助某人,它不起作用,因为DataBinding机制只能在一个方向上工作(从控件到对象)
如果我们在绑定对象中实例化新对象,则控件值不会跟随(它们不会更新),为此我们需要重置绑定
public void resetBindings()
{
foreach (Control c in Form1.Controls)
c.DataBindings.Clear();
bindingFields();
}
public void bindingFields()
{
txtCode.DataBindings.Add("Text",theVehicule,"vhCode");
...
..
txtActifInactif.DataBindings.Add("EditValue", theVehicule, "vhInactif");
}
private void barBtnSaveNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.Validate();
theVehicule.Save();
theVehicule = new tbVehicule(theVehicule.Session);
resetBindings();
}
使用上面的snipet它工作正常,可能是有一种更优雅的方式来重置绑定,我选择重新定义绑定,因为它是我发现的唯一一种方法,并且暂时有用。 。