ItemsControl.ItemsSource MVVM性能 [英] ItemsControl.ItemsSource MVVM performance
问题描述
我有一个(非虚拟化的)ItemsControl,它将其ItemsSource绑定到ViewModel实例的ObeservableCollection.现在,一旦加载了大量Model实例,就需要将所有ViewModel组件添加到该ObservableCollection中.如何在不使UI线程挂起的情况下添加大量ViewModel?
I have an (non-virtualized) ItemsControl that binds its ItemsSource to a ObeservableCollection of ViewModel instances. Now once the large amount Model instances is loaded all the ViewModel complemnents needs to be added to that ObservableCollection. How can I add a large amount of ViewModels without making the UI Thread hang?
我想UI线程会挂起,因为每次添加新项目时,ItemsControl都需要更新自身,并一遍又一遍地进行布局等.
I suppose the UI Thread hangs because each time a new item is added the ItemsControl needs to update itself and does layout etc. over and over again.
- 我应该暂停绑定吗? 项目然后恢复?如果可以,怎么办?
- 我应该覆盖 ObservableCollection实现一个 AddRange,所以只有1 CollectionChanged 为添加多个事件而触发了该事件 项目?或者替代 整个收藏?
- 还是更好 分别添加每个项目并调用 调度程序.为每个项目调用 分别地?所以我会解除封锁
- Should I suspend the binding add all items and then resume? If so, how?
- Should I override the ObservableCollection to implement an AddRange so only 1 CollectionChanged Event is fired for adding multiple items? Or alternatively just replace the whole collection?
- Or is it better to add each items separately and call Dispatcher.Invoke for each item separately? So I would unblock frequently.
您如何处理无法虚拟化的大型动态列表?
How do you handle large dynamic lists that can not be virtualized?
推荐答案
您可以创建一个从 ObservableCollection ,使您可以临时暂停 CollectionChanged 这样的事件:
You can create a a class derived from ObservableCollection which allows you to temporarily suspend CollectionChanged events like this:
public class SuspendableObservableCollection : ObservableCollection
{
private bool suspended;
public bool Suspended
{
get
{
return this.suspended;
}
set
{
this.suspended = value;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Reset));
}
}
protected override void OnCollectionChanged(
NotifyCollectionChangedEventArgs args)
{
if (!Suspended)
{
base.OnCollectionChanged(args);
}
}
}
这篇关于ItemsControl.ItemsSource MVVM性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!