简体   繁体   中英

Why is my DataGrid with a ObservableCollection<T> apparently not refreshing when I add or remove items from the collection?

I'm having a problem with a DataGrid and its underlying ObservableCollection. I want to add and remove rows programmatically from the collection and have the results appear in the DataGrid. While I expect that this will automagically happen for me, it doesn't. I've found that if I sort the data afterwards, that the rows will appear as I want them. Here's what I do:

  1. DataGrid's ItemsSource is set to my ObservableCollection<T>.

  2. User clicks button that fires an ICommand that removes rows with a value of X.

  3. What the user sees looks exactly the same: no rows are removed.

  4. User clicks column header to sort the DataGrid. Now the rows are removed.

What's going on here? The rows that I want removed, stay until I sort the columns. I found out something else as well. If I refresh the DataGrid.Items, the rows are removed. That code is simply:

this.dg.Items.Refresh();  //"dg" is my DataGrid

While this is not very MVVM, it works.

确保你直接绑定到你的ObservableCollection ,例如,你没有在任何Linq操作符上添加它,将它包装在集合视图/代理中等等。集合中任何不转发集合更改事件的转换/包装都将阻止网格被通知变更。

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