如何刷新 WPF DataGrid? [英] How to refresh a WPF DataGrid?
问题描述
我有一个带有一些数据的 WPF DataGrid
.您可以通过单独的窗口添加行.DataContext
是相同的,一个 LINQ-to-SQL
对象.绑定也是一样,我把ItemsSource
属性绑定到一个表上.
I have a WPF DataGrid
with some data. You can add rows through a separate window. The DataContext
is the same, a LINQ-to-SQL
object. Binding is also the same, I bind the ItemsSource
property to a table.
在另一个窗口中,当用户单击Save
时,我以编程方式创建一行并使用InsertOnSubmit
添加它.之后我使用 DataContext
的 SubmitChanges
方法.
In the other window, when the user clicks on Save
, I create a row programmatically and add it using InsertOnSubmit
. After that I use the DataContext
's SubmitChanges
method.
我的问题是 DataGrid
没有更新.如果我重新启动应用程序,我可以看到新行,所以它在数据库中,但我找不到刷新DataGrid
的方法.
My problem is that the DataGrid
isn't updated. If I restart the application I can see the new row, so it's in the database, but I couldn't find a way to refresh the DataGrid
.
到目前为止,我已经尝试在 DataGrid
的 BindingExpression
上使用 UpdateTarget
,但它没有帮助.我也试过 dataGrid.Items.Refresh()
—— 结果一样.我该如何解决这个问题?
So far I've tried to use UpdateTarget
on the BindingExpression
of the DataGrid
, but it didn't help. I've also tried dataGrid.Items.Refresh()
— same result. How can I fix this?
推荐答案
它没有更新的原因是 LINQ-to-SQL
没有实现 INotifyCollectionChanged
,所以WPF 无法判断 ItemsSource
已更新.解决此问题的最不可怕的方法是将您的 LINQ-to-SQL 结果复制到 ObservableCollection
- 当您执行 Insert 时,还要添加到 observable 集合.然后你会看到更新.
The reason it's not updating is that LINQ-to-SQL
doesn't implement INotifyCollectionChanged
, so WPF has no way to tell that the ItemsSource
has been updated. The least terrifying way to fix this, is to copy your LINQ-to-SQL results to an ObservableCollection
- when you do the Insert, also add to the observable collection. Then you'll see the update.
这篇关于如何刷新 WPF DataGrid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!