-1

I have a ListView that is bound to an Observable Collection of some object.. Selecting and item in the ListView displays a form. My business case is such when user toggles from one item to other in ListView and if there are any unsaved changes, user should be prompted of Yes/No/Cancel. If the user clicks on No then, the selected item should be removed from the List.

I have a ViewModel for the ListViewItem and inside IsSelected property I am prompting the user. Now when I remove the item from the Observable Collection, the IsSelected = True for the next time that is getting selected, I am getting error..

"Collection was modified; enumeration operation may not execute"..

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Arihant
  • 367
  • 1
  • 6
  • 22
  • 1
    you should really post some code. binding to your listbox, VM code and the snipped for the operation where the error is thrown – blindmeis Mar 16 '11 at 06:51
  • Does this answer your question? [VirtualizingStackPanel + MVVM + multiple selection](https://stackoverflow.com/questions/1273659/virtualizingstackpanel-mvvm-multiple-selection) – Herohtar Nov 24 '19 at 09:19

1 Answers1

1

I'm pretty sure you're running into problems because your program is removing the currently-selected item from the collection at the same time it's selecting it. Clicking on the item is changing SelectedItem for the ListView, and you're removing the item at the same time without setting a new value for SelectedItem.

What you probably want to do is create a property in the window's view model and bind the ListView's SelectedItem property to it. When the value of that property changes, you can prompt the user and then set SelectedItem to the appropriate value (i.e. to whatever the selected item should be after the currently-selected item is removed, or null if the collection's about to be empty) before you remove it from the underlying collection.

Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
  • I m facing same issue, I understood your solution. I used same way but still facing same issue. – PawanS Mar 25 '11 at 14:59