I want to be able to add a range and get updated for the entire bulk.
I also want to be able to cancel the action before it\'s done (i.e. collection changing besides
ObservableRangeCollection should pass a test like
[Test]
public void TestAddRangeWhileBoundToListCollectionView()
{
int collectionChangedEventsCounter = 0;
int propertyChangedEventsCounter = 0;
var collection = new ObservableRangeCollection<object>();
collection.CollectionChanged += (sender, e) => { collectionChangedEventsCounter++; };
(collection as INotifyPropertyChanged).PropertyChanged += (sender, e) => { propertyChangedEventsCounter++; };
var list = new ListCollectionView(collection);
collection.AddRange(new[] { new object(), new object(), new object(), new object() });
Assert.AreEqual(4, collection.Count);
Assert.AreEqual(1, collectionChangedEventsCounter);
Assert.AreEqual(2, propertyChangedEventsCounter);
}
otherwise we get
System.NotSupportedException : Range actions are not supported.
while using with a control.
I do not see an ideal solution, but NotifyCollectionChangedAction.Reset instead of Add/Remove partially solve the problem. See http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx as was mentioned by net_prog
Proof of need for OnPropertyChanged("Count")
and OnPropertyChanged("Item[]")
calls in order to behave as per ObservableCollection
. Note that I don't know what the consequences are if you don't bother!
Here is a test method that shows that there are two PropertyChange events for each add in a normal observable collection. One for "Count"
and one for "Item[]"
.
[TestMethod]
public void TestAddSinglesInOldObsevableCollection()
{
int colChangedEvents = 0;
int propChangedEvents = 0;
var collection = new ObservableCollection<object>();
collection.CollectionChanged += (sender, e) => { colChangedEvents++; };
(collection as INotifyPropertyChanged).PropertyChanged += (sender, e) => { propChangedEvents++; };
collection.Add(new object());
collection.Add(new object());
collection.Add(new object());
Assert.AreEqual(3, colChangedEvents);
Assert.AreEqual(6, propChangedEvents);
}
@Shimmy , swap the standard for your collection and change to an add range and you will get zero PropertyChanges. Note that collection change does work fine, but not doing exactly what ObservableCollection does. So Test for shimmy collection looks like this:
[TestMethod]
public void TestShimmyAddRange()
{
int colChangedEvents = 0;
int propChangedEvents = 0;
var collection = new ShimmyObservableCollection<object>();
collection.CollectionChanged += (sender, e) => { colChangedEvents++; };
(collection as INotifyPropertyChanged).PropertyChanged += (sender, e) => { propChangedEvents++; };
collection.AddRange(new[]{
new object(), new object(), new object(), new object()}); //4 objects at once
Assert.AreEqual(1, colChangedEvents); //great, just one!
Assert.AreEqual(2, propChangedEvents); //fails, no events :(
}
FYI here is code from InsertItem (also called by Add) from ObservableCollection:
protected override void InsertItem(int index, T item)
{
base.CheckReentrancy();
base.InsertItem(index, item);
base.OnPropertyChanged("Count");
base.OnPropertyChanged("Item[]");
base.OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
The C# summarized descendant.
More reading: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx
public sealed class ObservableCollectionEx<T> : ObservableCollection<T>
{
#region Ctor
public ObservableCollectionEx()
{
}
public ObservableCollectionEx(List<T> list) : base(list)
{
}
public ObservableCollectionEx(IEnumerable<T> collection) : base(collection)
{
}
#endregion
/// <summary>
/// Adds the elements of the specified collection to the end of the ObservableCollection(Of T).
/// </summary>
public void AddRange(
IEnumerable<T> itemsToAdd,
ECollectionChangeNotificationMode notificationMode = ECollectionChangeNotificationMode.Add)
{
if (itemsToAdd == null)
{
throw new ArgumentNullException("itemsToAdd");
}
CheckReentrancy();
if (notificationMode == ECollectionChangeNotificationMode.Reset)
{
foreach (var i in itemsToAdd)
{
Items.Add(i);
}
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
return;
}
int startIndex = Count;
var changedItems = itemsToAdd is List<T> ? (List<T>) itemsToAdd : new List<T>(itemsToAdd);
foreach (var i in changedItems)
{
Items.Add(i);
}
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
}
public enum ECollectionChangeNotificationMode
{
/// <summary>
/// Notifies that only a portion of data was changed and supplies the changed items (not supported by some elements,
/// like CollectionView class).
/// </summary>
Add,
/// <summary>
/// Notifies that the entire collection was changed, does not supply the changed items (may be inneficient with large
/// collections as requires the full update even if a small portion of items was added).
/// </summary>
Reset
}
}
Yes, adding your own Custom Observable Collection would be fair enough. Don't forget to raise appropriate events regardless whether it is used by UI for the moment or not ;) You will have to raise property change notification for "Item[]" property (required by WPF side and bound controls) as well as NotifyCollectionChangedEventArgs with a set of items added (your range). I've did such things (as well as sorting support and some other stuff) and had no problems with both Presentation and Code Behind layers.
You can also use this code to extend ObservableCollection:
public static class ObservableCollectionExtend
{
public static void AddRange<TSource>(this ObservableCollection<TSource> source, IEnumerable<TSource> items)
{
foreach (var item in items)
{
source.Add(item);
}
}
}
Then you don't need to change class in existing code.
I think AddRange is better implemented like so:
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
It saves you a list copy. Also if you want to micro-optimise you could do adds for up to N items and if more than N items where added do a reset.