如何刷新WPF DataGrid? [英] How to refresh a WPF DataGrid?

查看:1676
本文介绍了如何刷新WPF DataGrid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF DataGrid与一些数据。您可以通过单独的窗口添加行。 DataContext是一样的LINQ to SQL对象。绑定也是一样的,我将ItemsSource属性绑定到一个表。



在另一个窗口中,当用户点击保存时,我创建一个行以编程方式使用InsertOnSubmit添加。之后,我使用DataContext的SubmitChanges方法。



我的问题是DataGrid没有更新。如果我重新启动应用程序,我可以看到新行,所以它在数据库中,但我找不到一种刷新DataGrid的方法。



到目前为止, ve试图在DataGrid的BindingExpression上使用UpdateTarget,但没有帮助。我也试过dataGrid.Items.Refresh() - 相同的结果。如何解决这个问题?

解决方案

不更新的原因是LINQ to SQL不实现INotifyCollectionChanged WPF无法确定ItemsSource已被更新。解决这个问题的最不可怕的方法是将LINQ-to-SQL结果复制到ObservableCollection - 当您执行插入操作时,也添加到observable集合。然后你会看到更新。


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.

In the other window, when the user clicks on "Save", I create a row programatically and add it using "InsertOnSubmit". After that I use the DataContext's "SubmitChanges" method.

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.

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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆