Convert List to ObservableCollection in WP7

后端 未结 10 914
不知归路
不知归路 2020-12-25 10:10

I don\'t know if it\'s just too late or what, but I don\'t see how to do this...

What I\'m expecting to do, and what the object browser says is there, is this:

10条回答
  •  借酒劲吻你
    2020-12-25 10:35

    If you are going to be adding lots of items, consider deriving your own class from ObservableCollection and adding items to the protected Items member - this won't raise events in observers. When you are done you can raise the appropriate events:

    public class BulkUpdateObservableCollection : ObservableCollection
    {
        public void AddRange(IEnumerable collection)
        {
            foreach (var i in collection) Items.Add(i);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        }
     }
    

    When adding many items to an ObservableCollection that is already bound to a UI element (such as LongListSelector) this can make a massive performance difference.

    Prior to adding the items, you could also ensure you have enough space, so that the list isn't continually being expanded by implementing this method in the BulkObservableCollection class and calling it prior to calling AddRange:

        public void IncreaseCapacity(int increment)
        {
            var itemsList = (List)Items;
            var total = itemsList.Count + increment;
            if (itemsList.Capacity < total)
            {
                itemsList.Capacity = total;
            }
        }
    

提交回复
热议问题