by following this answer I coded almost same way. Below is part of my code.
XAML binding:
<cst:CustomDataGrid x:Name="grdItems" ItemsSource="{Binding myItems, IsAsync=True}" SelectedItemsList="{Binding SelectedItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ViewModel:
Protected Overrides Sub DeleteCurrent()
Dim msg As New UserMessage()
If SelectedItems IsNot Nothing Then
For Each SelectedItem In SelectedItems
myItems.Remove(SelectedItem)
Next
RaisePropertyChanged("Items")
End If
End Sub
Private m_myItems As ObservableCollection(Of item)
Public Property myItems() As ObservableCollection(Of item)
Get
Return m_myItems
End Get
Set(value As ObservableCollection(Of item))
m_myItems = value
End Set
End Property
Private m_SelectedItem As IList = New List(Of item)()
Public Property SelectedItems() As IList
Get
Return m_SelectedItem
End Get
Set(value As IList)
m_SelectedItem = value
' RaisePropertyChanged("SelectedItems")
End Set
End Property
Selection works perfectly fine. But when I am looping to remove selected each item, I am getting exception that "Collection was modified. Enumeration operation may not execute.". For example, I select 3 rows and press delete keyboard button, when I observe my SelectedItems object, count is 3 as expected but right after executing the line with myItems.Remove(SelectedItem), count goes down to 1. why is that happening, i couldnt figure out because I am not modifing SelectedItems but myItems.
PS; customdatagrid is exactly same code as the original post above. thats why i didnt add it here.
You're removing item from
myItems
which used asItemsSource
of the data grid. Removing item fromItemsSource
automatically followed by removing it fromSelectedItems
, and that behavior makes perfect sense (you can't keep an item selected when it is no longer in the data grid).That's why the error. You can't let the collection changed while enumerating through it.
One possible way to accomplish this is by copying selected items to temporary collection, to a temporary array, for example. Then enumerate the array instead of the original collection :
just copy selecteditems to new collection when doing foreach loop, e.g using ToArray linq extension method: