在WPF中对DataGrid进行TwoWay绑定

我有一个我正在使用的WPF DataGrid

var allLines = from Lines in ctx.InvoiceLines join PerPs in ctx.ProductsViews on Lines.ProductCode equals PerPs.ProductCode where (Lines.BranchNo == BrNo) && (Lines.Docket == Docket) select new { Lines.ProductCode, Lines.Description, Lines.Inv_Quantity, Lines.Grn_Quantity, Lines.Inv_Price,Lines.Grn_Price,Lines.Inv_Total, Lines.Grn_Total, Lines.AnalCode, Lines.Vat_Rate, Lines.GrnNo,Lines.Comment , PerPs.OuterUnits}; dgGrid.ItemsSource = allLines; 

我希望在更改任何值或添加新行时使用双向绑定来更新数据库。 那可能吗?

我的xaml代码是

                     

当我运行此代码时,除了PerP列之外的所有代码都是空的。

我很失落如何做到最好的方式,所以任何帮助将非常感激。

除“PerP”列之外, DataGridTextColumn所有Bindings都指定了两次路径。 例如:

  

在这里,您的Binding首先将路径指定为“ProductCode”,然后将其指定为“IsSelected”。 由于您在绑定到网格的集合中的对象上没有“IsSelected”属性,因此如果在调试器下运行此属性,则应在“输出”窗口中看到绑定错误。 如果删除这些绑定的Path=IsSelected ,则应正确绑定列值。

您的数据源是匿名类型的集合,因此var是必需的,但正如其他人所说,对该集合的双向绑定不适用于更新回源。

您的allLines变量是匿名类型的可枚举。 在C#中,匿名类型是只读的 – 无法编辑属性,并且无法保存更改。

尝试进行查询:

 var allLines = from Lines in ctx.InvoiceLines join PerPs in ctx.ProductsViews on Lines.ProductCode equals PerPs.ProductCode where (Lines.BranchNo == BrNo) && (Lines.Docket == Docket) select Lines; dgGrid.ItemsSource = allLines.ToList(); 

如果“allLines”变量是DataTable ,则可以将DataGrid的AutoGenerateColumns设置为true。
您还不需要使用“DataContext”属性,而是使用“ItemsSource”。
像这样的东西:

  

要在更改时更新数据库,请调用数据表的Update()方法,例如单击“保存”按钮。

如果“allLines”不是DataTable,那么删除这个地狱般的“var”关键字并告诉我们变量的真实性质=)