在 WPF 中更新 ObservableCollection 会导致屏幕闪烁;我该如何预防?
我有一个 ObservableCollection 以 MVVM 模式绑定到 WPFToolkit DataGrid。每隔 30 秒,我就会有一个后台线程在服务中查询一些数据。当它返回时,它将其编组到 UI 线程,并通过首先对集合调用 Clear() 然后对每个项目调用 Add() 来更新 ObservableCollection。发生这种情况时,数据会正确更新到屏幕,但是数据网格会闪烁。我怎样才能防止这种情况发生?
I have an ObservableCollection bound to a WPFToolkit DataGrid in an MVVM pattern. Every 30 seconds I have a background thread that is querying a service for some data. When it returns, it marshals it to the UI thread and updates the ObservableCollection by first calling Clear() on the collection and then calling Add() for each item. When this happens, the data is updated properly to the screen, however, the datagrid flickers. How can I prevent this from happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您一次清除然后添加每一项,那么您似乎只是替换了所有数据。您是否可以简单地将数据网格的项目源设置为包含新项目的新 ObservableCollection,而不是重新使用 ObservableCollection?
It appears you're simply replacing all of your data if you're clearing then adding each item one at a time. Instead of re-using your ObservableCollection, can you simply set your data grid's itemssource to a new ObservableCollection with your new items?
我为您的问题创建了一个简单但最强大的解决方案:
当您处于编辑模式时,我的集合类可防止集合更改事件。在清除项目之前启动“BeginEdit”。然后添加您的新项目。完成后,使用“CommitEdit”,视图将仅刷新一次。
如果用一个简单的列表框测试它,我在其中添加 1.000.000 个字符串项目。试试这个。这很有趣:)
从 list.BeginEdit() 中删除 // 并查看差异。再次约15秒< 1秒。
问候,
简
I created a simple but maximum powerfull solution for your problem:
The my collection class prevents collection changed events while you are in edit mode. Start "BeginEdit" before clearing the items. Then add your new items. When you are finished, use "CommitEdit" and the view will refresh only once.
If have tested it with a simple listbox, where i add 1.000.000 string items. Try this out. Its funny :)
Remove the // from list.BeginEdit() and see the difference. Its about 15 seconds agains < 1 second.
Greetings,
Jan