gpt4 book ai didi

c# - INotifyCollectionChanged——它多久触发一次(以及它们如何使它如此高效/快速)?

转载 作者:行者123 更新时间:2023-11-30 20:08:01 25 4
gpt4 key购买 nike

基本上,我想知道它在这里的实际效率如何。

示例代码:

void GetItems()
{
foreach (var item in items)
myObservableCollection.Add(item);
}

这不会每次都触发 CollectionChanged 事件导致 UI 每次都必须刷新吗?或者它这样做是为了等待 GetItems 函数完成?

基本上,WPF 似乎处理得很好,我想知道他们是怎么做到的。

最佳答案

Optimizing Performance: Data Binding提供了有关如何解决数据绑定(bind)的一些背景知识,包括不同项目源的性能影响。看看 Binding to an ItemsSource部分。

Consider a scenario in which you have a CLR List object that holds a list of employees that you want to display in a ListBox. To create a correspondence between these two objects, you would bind your employee list to the ItemsSource property of the ListBox. However, suppose you have a new employee joining your group. You might think that in order to insert this new person into your bound ListBox values, you would simply add this person to your employee list and expect this change to be recognized by the data binding engine automatically.

That assumption would prove false; in actuality, the change will not be reflected in the ListBox automatically. This is because the CLR List object does not automatically raise a collection changed event. In order to get the ListBox to pick up the changes, you would have to recreate your list of employees and re-attach it to the ItemsSource property of the ListBox. While this solution works, it introduces a huge performance impact. Each time you reassign the ItemsSource of ListBox to a new object, the ListBox first throws away its previous items and regenerates its entire list. The performance impact is magnified if your ListBox maps to a complex DataTemplate.

A very efficient solution to this problem is to make your employee list an ObservableCollection. An ObservableCollection object raises a change notification which the data binding engine can receive. The event adds or removes an item from an ItemsControl without the need to regenerate the entire list.

Update time for 1 item (ms)

  • To a CLR List object = 1656 ms
  • To an ObservableCollection = 20 ms

WPF 从不直接绑定(bind)到集合。如果将集合指定为绑定(bind)源,WPF 实际上会绑定(bind)到集合的 default view。 .

A collection view is a layer on top of a binding source collection that allows you to navigate and display the source collection based on sort, filter, and group queries, without having to change the underlying source collection itself. A collection view also maintains a pointer to the current item in the collection. If the source collection implements the INotifyCollectionChanged interface, the changes raised by the CollectionChanged event are propagated to the views.

关于c# - INotifyCollectionChanged——它多久触发一次(以及它们如何使它如此高效/快速)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7636752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com