提高装订速度
在阅读文档时,WPF 似乎使用反射来绑定到 CLR 对象。在我的应用程序中,我将 DataGrid
绑定到仅包含 250 个项目(每个项目有 8 个属性)的 IList
。 DataGrid
使用虚拟化,因此它仅获取 30 个左右项目的属性。这些属性都是简单的字符串,但仍然需要数百毫秒,如果与通过复杂的数据库查询生成该列表所需的 40 毫秒相比,这太长了。
有什么技巧可以提高绑定时间吗?
When reading the documentation it seems that WPF uses reflection to bind to CLR objects. In my app I bind a DataGrid
to a IList<T>
containing only 250 items (each with 8 properties). The DataGrid
is using virtualization, so it only fetches the properties for 30 items or so. The properties are all simple strings, and still it takes several hundreds of milliseconds, which is way too long if you compare it to the 40 msecs it took to generate that list via a complex database query.
Are there any tricks to improve the binding time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以,这是一个猜测,但它以前发生在我身上,值得一试。不过,在猜测之前,您是否分析过您的代码以确切了解哪些调用花费了最多时间?当您说使用绑定时时间会急剧增加时,我相信您,但我即将给出的建议可以通过分析结果来证明或反驳。不管怎样......
我不久前开发了一个应用程序,它生成了很多小的 UI 元素。每个元素都是
UserControl
的一个实例,并使用数据绑定来实现其外观。我注意到,当生成许多(200 多个)这些元素时,存在明显的滞后。我们使用 Prism 及其 ViewModelBase 类,将委托传递给 RaisePropertyChanged 方法,即,
问题在于 RaisePropertyChanged 的实现必须使用反射来获取字符串形式的属性名称。当很多(我的意思是很多)这些被解雇时,性能就会受到重大影响。
解决方案是什么?使用字符串代替函数对象。是的,这确实是全部。这有点糟糕,因为如果您重构该属性,您必须记住更改两件事,但老实说,在许多情况下,性能下降是不值得的。
不管怎样,试一试吧。如果大量 CPU 时间花费在
RaisePropertyChanged
内,这可能就是原因。So, this is a guess, but It's happened to me before and it's worth a shot. Before guessing though, have you profiled your code to see exactly which calls are taking the most time? I believe you when you say that the time increases dramatically when using binding, but the suggestion I am about to give can be proven or disproven with profiling results. Anyway...
I worked on an app a while ago that generated a lot of small UI elements. Each element was an instance of
UserControl
and used data binding for its appearance. I noticed that, when generating many (200+) of these elements there was an appreciable lag.We were using Prism and its
ViewModelBase
class, passing in delegates to theRaisePropertyChanged
method, i.e.,The problem with this is that the implementation of
RaisePropertyChanged
must use reflection to get the property name as a string. When a lot (and I mean a lot) of these were being fired off there was a significant performance hit.The solution? Use a string instead of the function object. Yes, that's really all it took. It stinks a bit as you have to remember to change two things if you ever refactor that property, but honestly the performance degradation is not worth it in many circumstances.
Anyways, give it a shot. If a lot of CPU time is being spent inside
RaisePropertyChanged
that is likely why.