简体   繁体   English

将 ItemsControl 绑定到 ObservableCollection<t> 比列表更有效<t> ?</t></t>

[英]Is binding an ItemsControl to an ObservableCollection<T> more efficient than a List<T>?

I have a render-heavy item template in an ItemsControl and want to minimize the recreation of child item templates when ItemsSource signals a change.我在ItemsControl中有一个渲染繁重的项目模板,并且希望在ItemsSource发出更改信号时尽量减少子项目模板的重新创建。 I am wondering if, because ObservableCollection can tell WPF precisely what has changed (as opposed to just the whole list), if it is more efficient in rendering changes to the collection, or if WPF is smart enough to reuse previous item views if it detects the same item is still in the changed list.我想知道,因为ObservableCollection可以准确地告诉 WPF 发生了什么变化(而不是仅仅告诉整个列表),它是否更有效地呈现集合的变化,或者 WPF 是否足够聪明,如果它检测到,可以重用以前的项目视图同一项目仍在更改列表中。

Your suspicion is correct.你的怀疑是正确的。 WPF will not reuse previous views. WPF 不会重复使用以前的视图。 If you replace the ItemsSource of an ItemsControl with a new List, it will create completely new views for each item in the list, even if the same items were in the old list.如果用新列表替换 ItemsControl 的 ItemsSource,它将为列表中的每个项目创建全新的视图,即使相同的项目在旧列表中也是如此。

You can test this yourself by putting a custom control in the ItemTemplate and adding a breakpoint or debug logging to its constructor.您可以通过在 ItemTemplate 中放置自定义控件并向其构造函数添加断点或调试日志记录来自行测试。 If you replace the ItemsSource with an identical list, you will see your control constructed once for each item in the list.如果用相同的列表替换 ItemsSource,您将看到为列表中的每个项目构造一次控件。 On the other hand, when an item is added to an ObservableCollection you will only see it called once.另一方面,当一个项目被添加到 ObservableCollection 时,您只会看到它被调用一次。

Note that the ItemsControl can reuse the container (such as ListBoxItem) if you are using a virtualizing panel and have container recycling enabled.请注意,如果您使用虚拟化面板并启用容器回收,则 ItemsControl 可以重用容器(例如 ListBoxItem)。 See Link .请参阅链接 It still can't reuse the contents of the container, however.但是,它仍然不能重用容器中的内容。

ObservableCollection only informs of addition and removal of objects - so perhaps not as precise as what you were expecting (if an object within the list changes, ObservableCollection will not fire off any notifications). ObservableCollection 仅通知对象的添加和删除 - 因此可能不如您预期的那么精确(如果列表中的 object 发生更改,ObservableCollection 将不会触发任何通知)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM