I have a strange problem that I do not understand. This is in Silverlight / WP7.
I populate an ObservableCollection with elements, and later I want to update each of the elements.
I managed to remove the code to reproduce the error. My XAML is just a ListBox and a button.
private ObservableCollection<int> Words = new ObservableCollection<int>(); public MainPage() { InitializeComponent(); listBox1.ItemsSource = Words; } private void button1_Click(object sender, RoutedEventArgs e) { List<int> numbers = new List<int>() { 1,2,3 }; foreach (var number in numbers) { var index = Words.IndexOf(number); if (index > -1) Words[index] = number; else Words.Add(number); } }
When you run the code for the first time, it fills the ObservableCollection with numbers 1, 2, and 3, and they appear in the ListBox.
The second time it runs all the code, but then an unhandled exception is thrown with the message "The parameter is incorrect."
The strange thing is that if I delete my line in the constructor, the one where I configured the ItemSource does not throw an error. The observed collection is updated as needed.
Also, if I comment on the line "Words [index] = number", it also works. Therefore, for some reason, when my ObservableCollection is set as the data source for the ListBox, I cannot replace the item.
Can someone explain why? (Or suggest a workaround?)
My decision; I changed the code from
if (index > -1) Words[index] = number;
to
if (index > -1) { Words.RemoveAt(index); Words.Add(number); }
This made the problem go away.