Hi,
I have an ObservableCollection that we manage items through an IEditableCollectionView. However when the collection is empty, and we try to add an item it throws an error as "Index was out of range. Must be non-negative and less than the size of the collection.". From reading a few articles it appears that without any items in the ObservableCollection, it can not determine the type of object to create.
As such we've implemented a temp workaround by checking if any items are in the ObservableCollection before trying to add the item using IEditableCollectionView.
' link to the list
Dim sp As SpecialCollection = DirectCast(Me.FindResource("SpecialCollectionResource"), SpecialCollection)
Dim spv As IEditableCollectionView = DirectCast(CollectionViewSource.GetDefaultView(Me.Example_List.Items), IEditableCollectionView)
spv.NewItemPlaceholderPosition = NewItemPlaceholderPosition.None' add a new item to the list
If sp.Count > 0 Then
' other items are in the collection, we can use the collection view for item manipulation
Dim item As Item = spv.AddNew()
With item
.SetName = "New"
.ID = sp.Count
End With
spv.CommitNew()
Else
' first item in collection, we have to update the source collection directly
Dim item As Item = New Item
With item
.SetName = "New"
.ID = sp.Count
End With
sp.Add(item)
' need to rebuild the dependant view(s)
sp.FireCollectionChanged()
End IfIn comments of this thread they mention changing the definition of the ObservableCollection from
PersonsList : ObservableCollection<Person> { }to
PersonsList<T> : ObservableCollection<T> where T : Person {}My own ObservableCollection is defined like this:
Public Class SpecialCollection
Inherits ObservableCollection(Of Item)How could I update this definition to allow IEditableCollectionView to work natively with an empty collection?
Other possible useful information, Item is just a normal class, the collection and collectionviewsource is defined in the xaml layer:
<local:SpecialCollection x:Key="SpecialCollectionResource" /><CollectionViewSource x:Key="SpecialCollectionViewResource"
Source="{StaticResource ResourceKey=SpecialCollectionResource}"><CollectionViewSource.SortDescriptions><cm:SortDescription PropertyName="SetName" /><cm:SortDescription PropertyName="ID" /></CollectionViewSource.SortDescriptions><CollectionViewSource.GroupDescriptions><PropertyGroupDescription PropertyName="SetName" /></CollectionViewSource.GroupDescriptions></CollectionViewSource>Thanks in advance,
Jay :)
If you shake a kettle, does it boil faster?