简体   繁体   中英

Datagrid Binding to ObservableCollection WPF

I have Datagrid binding to a ObservableCollection as a source, data grid cells is allowed the user to change the values, the problem when I change the cells values the ObservableCollection do not update

Here's my Datagrid code :

<DataGrid.Columns>
    <DataGridTextColumn Header="Item" Binding="{Binding Item.ItemName,Mode=TwoWay}" Width="100" IsReadOnly="False" />
    <DataGridTextColumn Header="Price" Binding="{Binding SalePrice,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
    <DataGridTextColumn Header="Qtn" Binding="{Binding Quantity,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
    <DataGridTextColumn Header="Totla" Binding="{Binding Total,Mode=TwoWay}" Width="100" IsReadOnly="False"  />
</DataGrid.Columns>

any suggestions

The WPF DataGrid uses a transaction scope when its cells are edited. What that means is that after changing a cell, a 'commit' is needed in order to persist the change. To force a commit, you can use the Tab key or the Enter key.

Lots of people will type a new value into a cell and then mouse into another cell or another control altogether. When this happens the DataGrid does a 'cancel' on the transaction and thus the change is not persisted in the underlying collection. In fact, almost anything other than Tab or Enter (or losing focus) will raise a cancel on the transaction.

If you want to capture changes regardless of what key the user pressed, then the underlying class should implement IEditableObject. This allows the view model to force a commit and persist the changed cell.

It's a known 'gotcha' on WPF DataGrids. There's a lucid discussion on it here http://blogs.msdn.com/b/vinsibal/archive/2009/04/07/5-random-gotchas-with-the-wpf-datagrid.aspx

Even more subtle 'gotchas' on the same subject are discussed here http://blogs.msdn.com/b/vinsibal/archive/2009/04/14/5-more-random-gotchas-with-the-wpf-datagrid.aspx

Possible duplicate of Why isn't a property in my ViewModel updated when DataGrid changes?

Implement RaisePropertyChanged to your properties(SalesPrice,Quantity,Total)'s Set method

ObservableCollection only notifies about collection changed events like adding,removing items from collection, The underlying class properties of ObservableCollection should implement the RaisePropertyChanged Events seperetly to detect changes in them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM