0

在我的 Winform 项目中,我有一个简单的详细信息表单,我们可以在其中添加新的、编辑和保存持久对象,直到这里一切正常。

编辑控件是通过from构造函数中的代码绑定的,第一次创建的时候也是通过form构造函数传递的第一个新对象

现在我想实现一个Save and New方法,但没有成功

我试过了,假设 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

4

1 回答 1

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

   }

使用上面的片段它工作正常,可能是有一种更优雅的方式来重置绑定,我选择重新定义绑定,因为它是我发现的唯一一种方法,并且目前有效。.

于 2014-01-07T14:01:13.607 回答