TwoWay binding on a DataGrid in WPF

吃可爱长大的小学妹 提交于 2019-11-29 15:36:47

All the Bindings for your DataGridTextColumn besides the "PerP" column are specifying the path twice. For example:

<DataGridTextColumn Width="Auto" Header="ProductCode"  Binding="{Binding ProductCode, Mode=TwoWay, Path=IsSelected, UpdateSourceTrigger=PropertyChanged}"/>

Here your Binding is first specifying the path to be "ProductCode" and then also specifying it to be "IsSelected". Since there is no "IsSelected" property on the objects in the collection that you are binding to the grid, if you run this under the debugger you should see binding errors in the Output window. If you remove the Path=IsSelected for those bindings then the column values should be bound correctly.

Your datasource is a collection of an anonymous type so the var is necessary, but as others have said two-way binding to that collection isn't going to work for updates back to the source.

Your allLines variable is an enumerable of an anonymous type. In C# anonymous types are read-only - the properties cannot be edited, and the changes can't be saved.

Try making your query:

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

If the "allLines" variable is a DataTable, you could just set your DataGrid's AutoGenerateColumns to true.
You also need not to use the "DataContext" property, but "ItemsSource" instead.
Something like this:

<DataGrid ItemsSource="{Binding Path=allLines.DefaultView}" ... />

To update back the database on changes, call the Update() method of your datatable, on a "Save" button click for example.

If "allLines" is not a DataTable, then remove this hellish "var" keyword and tell us the true nature of the variable =)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!